How to perform case-insensitive sorting in JavaScript?

Jérôme Verstrynge picture Jérôme Verstrynge · Jan 25, 2012 · Viewed 113.4k times · Source

I have an array of strings I need to sort in JavaScript, but in a case-insensitive way. How to perform this?

Answer

Ivan Krechetov picture Ivan Krechetov · Mar 10, 2012

In (almost :) a one-liner

["Foo", "bar"].sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
});

Which results in

[ 'bar', 'Foo' ]

While

["Foo", "bar"].sort();

results in

[ 'Foo', 'bar' ]