Why JavaScript sorts wrongly


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 does JavaScript give wrong sort results?

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

Comparing Strings and Numbers in JavaScript

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.

Use JavaScript Comparer Functions to guarantee sorts

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 read Quirky Quirky JavaScript: Episodeย One.

Processingโ€ฆ
Awesome!

Related

 


Discover more from CodeKraft

Subscribe to get the latest posts sent to your email.

One thought on “Why JavaScript sorts wrongly

  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 comment

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