Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform case-insensitive sorting array of string in JavaScript?

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

like image 493
Jérôme Verstrynge Avatar asked Jan 25 '12 01:01

Jérôme Verstrynge


People also ask

Does localeCompare ignore case?

localeCompare() enables case-insensitive sorting for an array.

Is JavaScript match case insensitive?

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.

Can you sort an array in JavaScript?

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.


1 Answers

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' ] 
like image 150
Ivan Krechetov Avatar answered Oct 06 '22 13:10

Ivan Krechetov