I am trying to sort the following array that contains negative numbers and the function sort()
does not sort it correctly (precisely the negative numbers)
let aa = [1,-2,3,-4,5].sort();
console.log(aa);
It returns 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?
Array#sort( )
sorts in UTF-8 order , after converting elements to strings.According to the above, first take the
-
, and then the number itself. And, in UTF-8 encoding, the value of2
is less than the value of4
. And that of the sign-
, less than that of any digit or letter.If you want to sort the content as numbers, you have to pass it a function as an argument, of the type
This function will receive 2 of the values of the array, and has to return
< 0
Yesa < b
== 0
Yesa == b
> 0
Yesa > b
Example:
Departure:
Note: in the example, it is certain that 2 elements will never be the same, so we save ourselves the check (we never return
0
).