Sorting Numbers Correctly
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.
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.
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:
- 0 If a and b are equal
- A number below 0 if a is smaller than b
- 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.