I have an array of strings I need to sort in JavaScript, but in a case-insensitive way. How to perform this?
In a one-liner
["Foo", "bar"].sort((a, b) => a.localeCompare(b, 'en', {'sensitivity': 'base'}));
Which results in
[ 'bar', 'Foo' ]
Replace 'en'
with your desired locale if needed, see method reference and more information. Method widely available since 2017.
Important note from MDN:
When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare() method.
Example:
const collator = new Intl.Collator('en'); // replace 'en' with your desired locale if needed
["Foo", "bar"].sort(collator.compare)
Also widely available since 2017. Remember to reuse the collator
, instead of creating new every time.
While simply
["Foo", "bar"].sort();
results in
[ 'Foo', 'bar' ]