Workds for all but one test case

So I wrote:

function getIndexToIns(arr, num) {
  if (arr.length == 0){
    return 0; 
  else {
    var index = 0; 
    for (var i=0; i<arr.length; i++){
      if (num <= arr[i]){
        return index; 
  return arr.length; 

It says

getIndexToIns([5, 3, 20, 3], 5) should return 2

But this code should return 2.

A function immediately stops the very first time it encounters a return stamement.

I know but that should still return index 2.

Why? The the function will return and immediately halt before reaching index 2. Return means immediately stop and return to the calling content. As soon as the return statement is encountered, the function can do absolutely nothing else.

Assume this is the test: getIndexToIns([3, 3, 5, 20], 5);

It goes to the else block and index is 0.

Is 5 <= 3? No, increment index to 1.
Is 5 <= 3? No, increment index to 2.
Is 5 <= 5? Yes, return index which is 2.

Woops, I misread your < as an >. This line is your problem. Sort orders your array as if it was strings.

So your array is sorted as [20, 3, 3, 5]

I don’t think so bc it worked for every other case. Also, I just added console.log(typeof arr[1]) right underneath the sort line and it printed out number.

It’s in the basic documentation on how Javascript works:

The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

const months = ['March', 'Jan', 'Feb', 'Dec'];
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
// expected output: Array [1, 100000, 21, 30, 4]

1 Like

In order to pass the challenge, you will want to look at the part of the documentation that specifically talks about how to use sort with numbers and what the compare function is.
That will give you the answer you are looking for.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.