A little known fact about the array sort method in Javascript

ProgrammingJul 2021

Little known fact about the sort function for arrays in Javascript. It sorts the items inside the array based on their UTF-16 code. This is useful when the contents are strings. But, if I’m sorting an array of numbers, it does so by first converting all numbers to strings and then sorting them based on their position on the UTF-16 table.

Good news is that the sort function does take a callback function with two arguments representing the two items being compared. In an array of numbers, if the difference between the two arguments is a positive number, that means that the first is bigger than the second. If the difference is a negative number, the second is bigger than the first.

This approach can also be harnessed for more unique examples. Below, for example, I have an array of human needs that I want to sort, and in the callback I provide a correct order template that is then used for the sorting:

No items found.