0

I am using sort() for quite sometime in JavaScript but today I encountered something which is confusing.

Example 1
Here is a snapshot of my chrome console where I am trying to sort an array.

enter image description here Step 1. aa is an array decalred with some integer values.
Step 2. Result of aa.sort() is unexpected, as yellow highlights clearly shows that that array is not sorted.
Step 3. Sorting the array using a compare function ** inside the sort. And this works perfectly.


Example 2
Here is another example -
enter image description here.
Simply using **sort()
sorts the array in default ascending order while same is not happening in Example 1.

I want to know exactly what goes inside sort() method.

Pranjal Successena
  • 907
  • 1
  • 11
  • 24

4 Answers4

5

See MDN:

The default sort order is according to string Unicode code points.

And when you sort by string, 100 is smaller than 20 because it tests character-by-character.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

From this post:

By default, the sort() method sorts the values as strings in alphabetical and ascending order.

This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce an incorrect result when sorting numbers.

You can fix this by providing a "compare function".

1

Array.prototype.sort() is a higher order function. You can use a compare function as an argument to get right results:

let myArray = [6,7,3,5,4,1,45];
myArray.sort((n1, n2) => n1 - n2);
// result => [1, 3, 4, 5, 6, 7, 45]
  • The question always says they can pass a sort function to get the correct results. They are asking why they don't get the results they expect with the default sort function. – Quentin Aug 12 '18 at 07:52
-2

Numbers are converted to strings. So it thinks like this:

[a, aa, aaa, b, bb, bbb] // makes sense

[1, 11, 111, 2, 22, 222] // um, only makes sense as strings!
bob
  • 7,539
  • 2
  • 46
  • 42