JVerstry JVerstry - 2 months ago 12
Javascript Question

How to perform case insensitive sorting in Javascript?

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

Answer

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' ]
Comments