Reputation: 469
I would like to sort an array with strings alphabetically (regardless of capital or lower letters).
For example b, C, A should become A, b, C. < br />
But since .sort is case sensitive (something with ASCII) it becomes A, C, b < br />
var myArray = [ 'b', 'A', 'C' ];
myArray.sort();
console.log(myArray);
Link to fiddle: http://jsfiddle.net/x93N8/
How can I fix this?
Upvotes: 0
Views: 1942
Reputation: 11693
myArray.sort(
function(a, b) {
if (a.toLowerCase() < b.toLowerCase()) return -1;
if (a.toLowerCase() > b.toLowerCase()) return 1;
return 0;
}
);
lease note that I originally wrote this to illustrate the technique rather than having performance in mind. Please also refer to answer @Ivan Krechetov for a more compact solution.
Upvotes: 0
Reputation: 382167
You can do this :
myArray.sort(function(a,b){
a = a.toLowerCase(); b = b.toLowerCase();
return a>b ? 1 : a==b ? 0 : -1;
});
Upvotes: 4
Reputation: 26183
You need to lowercase the strings when comparing them in the sort function like this:
var myArray = [ 'b', 'A', 'C' ];
myArray.sort(function(a,b){
var alc = a.toLowerCase(), blc = b.toLowerCase();
return alc > blc ? 1 : alc < blc ? -1 : 0;
});
To quote the ECMAScript 5 spec:
15.4.4.11 Array.prototype.sort (comparefn)
The elements of this array are sorted. The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y.
You can find the full ECMAScript spec here: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf and read all about sorting on page 140.
You can also read about the sort method here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
You can see the updated fiddle here: http://jsfiddle.net/x93N8/2/
Upvotes: 1