Sorting in JavaScript


What does the JavaScript snippet below return?

[1,2,3,10,20,30].sort();

If you think it would be [1, 2, 3, 10, 20, 30], you are in for a big surprise!

[1,2,3,10,20,30].sort();
// [1, 10, 2, 30, 3, 30]

Why?

The default sort in JavaScript is the lexicographic (alphabetical) sort. All operands are cast into strings before comparison; see this section of the JavaScript spec.

It is possible to override this by passing a comparer function to the sort method.

PS: This is like the bash sort command which also will default to strings unless the number type is specified

String Vs Number Comparisons

20 > 3
// true

'20' > 3
// true. String vs Number

'20' > '3'
// false. String vs String

Why is ’20’ > ‘3’ false?

Since both are strings, the sort compare operation starts comparing both strings by their individual characters. The comparison has a quick exit on the first character mismatch.

Since ‘2’ > ‘3’ is not true; the remaining characters are immediately discarded and the result is set to false. The ‘0’ doesn’t even get looked at.

So what do I do? Comparer Functions

Want to sleep well at night? Always pass in a comparer function when using sort.

[1, 2, 3, 10, 20, 30].sort((a,b) => a - b);

// [1, 2, 3, 10, 20, 30]

// Reverse order
[1, 2, 3, 10, 20, 30].sort((a,b) => b - a);

// [30, 20, 10, 3, 2, 1]

You can use this to sort almost any list; you can sort objects by their sizes, arrays by their length or anything based on your wishes.

// Sort array of objects by number of fields
[
{a: 1, b: 2, c: 3 },
{ a: 10, b: 20}
].sort((a,b) => Object.keys(a).length - Object.keys(b).length);

// [
//    { a: 10, b: 20},
//    {a: 1, b: 2, c: 3 }
// ]

// Sort arrays based on length
[
[1, 2, 3],
[10, 20]
].sort((a,b) => a.length - b.length);

// [
//   [10, 20],
//   [1, 2, 3]
// ]

There you go; some tips on sorting with JavaScript! Now you know a little more JS hopefully.

Related

1 Comment

·

Leave a Reply

  1. Our team uses sort more on the backend. But I always like to be up to speed on how to do it in JS if necessary. This is well thought out explanation of those little quirks the sort method has. Cheers!

    Like

Leave a Reply to Mitchell Opitz Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.