I have an array of strings I need to sort in JavaScript, but in a case-insensitive way. How to perform this?
localeCompare() enables case-insensitive sorting for an array.
Case-insensitive: It means the text or typed input that is not sensitive to capitalization of letters, like “Geeks” and “GEEKS” must be treated as same in case-insensitive search. In Javascript, we use string. match() function to search a regexp in a string and match() function returns the matches, as an Array object.
JavaScript Array sort()The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
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' ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With