DEV Community

Kenneth Lum
Kenneth Lum

Posted on • Edited on

3

Two things to immediately take note of when using JavaScript's array sort() method

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 ]
Enter fullscreen mode Exit fullscreen mode

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 ]
Enter fullscreen mode Exit fullscreen mode

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay