Oliver Jumpertz

Sorting Numbers Correctly

Category: JavaScript

Share this snippet to:

const numbers = [20, 4, 26, 5, 11, 7, 0, 1];
// ascending
numbers.sort((a, b) => a - b);
// descending
numbers.sort((a, b) => b - a);

Explanation

Arrays can contain any form of data. Even more important, they can contain a mixed list of data types. No one can stop you from adding strings, numbers, objects, and more to an array. This is why the default implementation of `Array.sort“ somehow needs to make a few assumptions to allow itself to work at least somehow for all types an array can contain.

In this case, the assumption is that all types in JavaScript can be converted to strings, which is why by default, Array.sort converts all values to strings and then compares these strings against each other. This is why, without a callback, Array.sort gives you a lexically sorted array instead of what you probably would have expected.

As there are still other data types in JavaScript you’d probably like to sort, Array.sort takes a callback, which allows you to override the default compare function. The compare function is only expected to return the following results:

  1. 0 If a and b are equal
  2. A number below 0 if a is smaller than b
  3. A number above 0 if a is larger than b

In case of numbers, you only need to subtract b from a to get these results. If a is bigger than b, subtracting b from a will yield a positive number. If a is smaller than b, the result will be negative. If a equals b, the result is 0. This leads to an ascending order. If you want an descending order, you only need to subtract a from b, and done.


Share this snippet to: