JavaScript’s Array.prototype.sort sorts numbers as if they were strings

2019-11-30

This:

[1, 2, 3, 10].sort()

outputs this:

[1, 10, 2, 3]

because apparently, elements are converted to strings before comparing them.

To compare numbers correctly, we can use a compare function:

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

which will output what we would expect:

[1, 2, 3, 10]

A more detailed article here: https://www.sitepoint.com/sort-an-array-of-objects-in-javascript/