Sort method help for a newbie

I am new to JavaScript and am currently completing the part of the course called Basic Scripting having a lot of struggle in understanding why my solutions don’t work. Could someone please take a look at the code and explain why the code i wrote is not passing for the exercise? Thank in advance!

So the condition for the exercise was:

Blockquote Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.
For example, getIndexToIns([1,2,3,4], 1.5) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1).
Likewise, getIndexToIns([20,3,5], 19) should return 2 because once the array has been sorted it will look like [3,5,20] and 19 is less than 20 (index 2) and greater than 5 (index 1).

I wrote the code:

function getIndexToIns(arr, num) {
  arr.sort();

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] >= num) return i;
  }

  return arr.length;
}

getIndexToIns([40, 60], 50);

Since the sort method is already built into Java Script as long as i googled, but the correct version of this code is this:

function getIndexToIns(arr, num) {
  arr.sort((a, b) => a - b);

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] >= num) return i;
  }

  return arr.length;
}

getIndexToIns([40, 60], 50);

Could someone please explain me why?

hello and welcome to fcc forum :slight_smile:

  • you need to define “sort” callback method to clarify what kind of sorting do you intend to apply on that array

you can read about them more in detail from mdn docs, happy reading Array.prototype.sort() - JavaScript | MDN

2 Likes

If compareFn is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units 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 the Unicode order. All undefined elements are sorted to the end of the array.

So, you can confirm like this:

> array1 = [1, 30, 4, 21, 100000];
[ 1, 30, 4, 21, 100000 ]
> array1.sort()
[ 1, 100000, 21, 30, 4 ]

> array1 = [1, 30, 4, 21, 100000];
[ 1, 30, 4, 21, 100000 ]
> array1.sort((a, b) => a - b);
[ 1, 4, 21, 30, 100000 ]

To compare array values as numbers, a function for comparison must be specified as an argument to the sort() method.

1 Like

Oh, thank you both for the explanations! :sparkling_heart:

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