Where do I belong: my code passes all tests but one, why?

Hi all,

I’ve been scratching my head for a while now. My solution to “Where do I belong?” passes all tests but one:

function getIndexToIns(arr, num) {
  arr.sort();
  
  var i = 0;
  
  while (num > arr[i]) {
    if (num < arr[i]) { return i; }
    else i++;
  }
  
  return i;
}

getIndexToIns([5,3,20,3], 5);

That data passed in to the function should return 2 (test no. 5), but I get a 0 back instead. Any suggestions on why? Is it because there’s a 5 in arr, same as the num?

Check the result of this in the console:

> [5, 3, 20, 3].sort()
[20, 3, 3, 5]

The sort default is:

the array is sorted according to each character’s Unicode code point value, according to the string conversion of each element."

The string “20” comes before the string “3”. So because your array is not properly sorted according to the numeric values, the result is 0. Note that the comparison num > arr[i] is made with numerical values and not with the string converted values.

So, how to fix it? You need to pass to the .sort() method a compareFunction that properly sorts numbers.

This can be simply:

function compareNumbers(a, b) {
  return a - b;
}

I recomend reading Array.prototype.sort() - JavaScript | MDN to understand better how the sort method works and how the compare functions need to be built.

5 Likes

Hey Thomas,

When you use sort(), you need to provide it with a compare function. Here’s a quick explanation from MDN:

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, “Banana” comes before “cherry”. In a numeric sort, 9 comes before 80, but because numbers are converted to strings, “80” comes before “9” in Unicode order.

That’s not the easiest to understand explanation. At the 3 min mark, this YouTube video does a fairly decent job of explaining how compare functions work: https://youtu.be/L9ct-OjtKPM

At the moment, your arr.sort() method is converting the numbers to strings and comparing their unicode values. This isn’t going to give you the right results.

It also looks like your if/else statement is formatted incorrectly (missing a { somewhere), but this may just be the forum’s formatting.

4 Likes

Extra thanks, @zelite. :wink:

All working great now, thank you so much @zelite and @joshamore!

1 Like
Where do I belong *****my solution******

function getIndexToIns(arr, num) {

arr.push(num);

function sort(a,b){

return a - b ;

}

return arr.sort(sort).indexOf(num);

}

getIndexToIns([40, 60], 50);

This was very useful. Thanks.