While sorting an array of objects recently, I needed to sort by an identifier prefixed with two letters and ended with numbers. An example is “AQ110” — you might be tempted to reach for a library, but you can achieve this in Javascript with very little code.
Say hello to localCompare.
I had a list of values that looked like this:
- AQ2
- AQ110
- AQ19
- AQ190
- AQ64
- AQ5
The lettering didn’t matter so much, but the numbers did. By default, just using a plain old .sort() will not be enough. If you were to use .sort() by itself, it would get tripped up on high numbers starting with the same value (eg. 10, 110, 11 and so on).
sites.sort((a, b) => { return a.meta.siteNumber.localeCompare(b.meta.siteNumber, 'en', {numeric: true, sensitivity: 'base'}); });
The first argument of the localeCompare function is the value being compared against. The second is the locale, and the last argument is the configuration options. The important option here is numeric: true
which tells localCompare
that we want to parse the numbers in our value. We also use sensitivity: 'base'
to ensure our comparison is case-insensitive.
As you can also see, my array contains objects and I am sorting on a specific property called siteNumber
which is a meta value for the item I am iterating.
That’s all there is to it. There are many more uses of localCompare, but comparing numerical and string values strings is one of its most substantial capabilities.