JavaScript Pitfalls & Tips: Sort

JavaScript Quiz:

What would be the result of the above JavaScript code? You may expect [2, 10, 456, 3548] since the array seem to be an integer array and JavaScript would sort it in numeric order. But, the correct result is as follows:

1
[10, 2, 3548, 456]

It is because the default comparison function of Array.prototype.sort() is the string comparison after converting each element to string.

Why the default sort function of JavaScript array as string comparison? I guess that the reason is the array type in JavaScript is for general types. For example, the following is a valid array of JavaScript.

1
var a = [ '13', 'Bob', 20, NaN, Infinity ];

Since the default sort function is for string, a.sort() works consistently and with no error.

Solutions

But, if you want to sort the array as numbers, how can you make it? There are two ways.

Comparison function for Number

You may supply a comparison function for numbers as follows:

1
[10, 2, 456, 3548].sort(function(a,b) { return a - b })

If you use ES2015 or above, you may use arrow function to keep it simple:

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

Typed array (ES2015 above)

You may think the sort function should sort in numeric order if the array is numeric typed array. You are right if you make the array numeric typed. JavaScript supports typed array.

ES2015 introduced TypedArray as a view of binary data buffer. But you may use it as an array of the same type. So you can make the general array as typed array and sort as follows:

1
Float64Array.from([10, 2, 456, 3548]).sort()

Note that there is no Int64Array type since the widest integer in bitwise operation is 32-bit.