Get in touch

Send an email to: lammers@gmail.com.
Or find me online at: Github, X

Sort with localeCompare()

The localeCompare() method can be used compare 2 strings and get the order.

'a'.localeCompare('c') // -1
'd'.localeCompare('c') // 1
'c'.localeCompare('c') // 0

In combination with the sort method it can be used to sort an array.

const arr = [{ id: 'b' }, { id: 'c' }, { id: 'a' }]
arr.sort((a, b) => a.id.localeCompare(b.id))

It also supports optional locales and options parameters. See MDN for more details about this