Where do I Belong - Not able to pass some test cases

Tell us what’s happening:
I tried to solve this problem using the code below but I am not able to pass some test cases, which are:

  • getIndexToIns([10, 20, 30, 40, 50], 30) should return 2.
  • getIndexToIns([5, 3, 20, 3], 5) should return 2 .
  • getIndexToIns([], 1) should return 0 .
  • getIndexToIns([], 1) should return a number.

Please tell me what do I need to change in my code to pass the test cases above.

Your code so far


function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  arr.sort();
  for (var i = 0; i <= arr.length-1; i++) {
    if(arr[i] > num) {
      var val = i-1;
      if(arr[i-1]<num) {
        val = i;
      }

      if(arr = num) {
        val = i;
      }
    
    }

    if(num > arr[arr.length-1]) {
      val = arr.length;
    }

    
  } 
  return val;
}

getIndexToIns([40, 60], 50);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong/

proper comparison operator == or ===
compare the element arr[i] instead of the array with the number

 if(arr = num) { 
        val = i;
      }

return index immediately instead of letting it mutate or returned last

  return val; 

First thing i can see is that your for loop should have

 if(arr[i] >= num)

at line 5;

AND i believe if you sort array [5, 3, 20, 3] then it gives [20,3,3,5] since it only checks for the initial number which in 20 is 2 resulting an array like [ 20, 3, 3, 5]

So, now you need to return 0 if arr=[] and find a way to sort this array [5, 3, 20, 3] correctly

I changed the stuff as you said it still isn’t solving the problem. Rather one more test case shows unpassed.

So, do I need to write a proper sorting method?

Learn more about the sort() method and sort the arrays after that.