Error sorting an array with negative numbers with JavaScript's sort function

Question:

I am trying to sort the following array that contains negative numbers and the sort() function does not sort() it correctly (precisely the negative numbers)

let aa = [1,-2,3,-4,5].sort();
console.log(aa);

Return to me:

[-2, -4, 1, 3, 5]

But I expected the order from smallest to largest

[-4, -2, 1, 3, 5]

What am I doing or misinterpreting?

Answer:

Array#sort( ) sorts according to UTF-8 order , after converting elements to strings.

According to the above, first take the - , and then the number itself. And, in UTF-8 code, the value of 2 is less than the value of 4 . And that of the sign - , less than that of any digit or letter.

If you want to order the content as numbers, you have to pass it a function as an argument, of the type

SortFunction( a, b )

This function will receive 2 of the values ​​of the array, and must return

  • < 0 if a < b
  • == 0 if a == b
  • > 0 if a > b

Example:

[1,-2,3,-4,5].sort( function( a, b ) { return a < b ? -1 : 1; } );

Exit:

[-4, -2, 1, 3, 5]

 console.log([1,-2,3,-4,5].sort( function( a, b ) { return a < b ? -1 : 1; } ));

Note: in the example, it is certain that 2 elements will never be the same, so we save ourselves from checking it (we never return 0 ).

Scroll to Top