How to sort by string length

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the algorithms category.

Last Updated: 2024-05-07

I wanted single digit house numbers (e.g. 2, 3) to appear before double digit ones (e.g. 21, 78) in an autocomplete. How should this kind of sorting be done?

Online I saw the following algorithm:

// ascending order
houseNumbers.sort((a, b) => a.length - b.length)

But how does this work?

Imagine the following input:

32 | 415 | 9

The lengths are:

2 | 3 | 1

Taking these pairwise, we have

(32, 415), (32, 9), and (415, 9)

Computing the subtraction of their lengths gives

2 - 3 | 2 - 1 | 3 - 1

-1    | 1     | 2

Connecting this calculation to the pairs (denoted (a,b))

Since ascending order means a < b < c, from the numbers above we see that: - 32 comes before 415 - 9 comes before 32 - (rest not necessary...)