I’ve been using Javascript for 2 years now and can not remember ever having to sort collections. 95% of what I am doing is backend services work and I try to off load as much data manipulation to the databases, but this week I have had 7 instances of having to sort data.
This caught me out:
For a given collection:
const collection = [ {name: "Dave"}, {name: "Donna"}, {name: "dave"}, {name: "Derek"}, {name: "Dave"},];
Sorted with:
collection.sort( (a,b) => { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; })
Returns this:
[ { name: 'Dave' }, { name: 'Dave' }, { name: 'Derek' }, { name: 'Donna' }, { name: 'dave' } ]
Which is not what I need.
.localCompare to the rescue
collection.sort( (a, b) => a.name.localeCompare(b.name) )
Returns this:
[ { name: 'dave' }, { name: 'Dave' }, { name: 'Dave' }, { name: 'Derek' }, { name: 'Donna' } ]
But there is more
.localCompare method has additional options. For the same collection above, this
collection.sort( (a, b) => a.name.localeCompare(b.name, 'en', { sensitivity: 'base' }) )
Returns this:
[ { name: 'Dave' }, { name: 'Dave' }, { name: 'dave' }, { name: 'Derek' }, { name: 'Donna' } ]
Be aware that full implementation of .localCompare in Node.js is dependant on the version you are running.