There are two things to take note of, when using JavaScript's array sort()
method.
The first one is easier to remember: it is sorting in place. That is, no new array is created. This is easier to remember, because in ES5, the only two array methods that return a new array is slice()
and concat()
. So sort()
doesn't return a new array and therefore it must be sorting in place.
The second one is, even when all the elements are numbers, it is sorted as if they are strings. So it is by lexical order (by unicode UTF-16 order).
> arr = [1, 3, 5, 11111111]
[ 1, 3, 5, 11111111 ]
> arr.sort()
[ 1, 11111111, 3, 5 ]
To sort them numberically, simply supply a comparison function:
> arr = [1, 3, 5, 11111111, 20, 30]
[ 1, 3, 5, 11111111, 20, 30 ]
> arr.sort((a, b) => a - b)
[ 1, 3, 5, 20, 30, 11111111 ]
In coding competition measured by time to finish, or in an online interview that requires the code to be running successfully for all the test cases within 10 to 15 minutes, this can be important.
So the two things to remember are: (1) sorted in place (2) as if they are strings.
Top comments (0)