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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more