我有一个字符串数组,我需要在JavaScript中排序,但以不区分大小写的方式。如何做到这一点?
当前回答
你也可以使用Elvis操作符:
arr = ['Bob', 'charley', 'fudge', 'Fudge', 'biscuit'];
arr.sort(function(s1, s2){
var l=s1.toLowerCase(), m=s2.toLowerCase();
return l===m?0:l>m?1:-1;
});
console.log(arr);
给:
biscuit,Bob,charley,fudge,Fudge
localeCompare方法可能很好…
注意:Elvis操作符是if then else的“三元操作符”的缩写形式,通常带有赋值。 如果你从侧面看,它看起来像猫王… 例如:
if (y) {
x = 1;
} else {
x = 2;
}
你可以使用:
x = y?1:2;
也就是说,当y为真时,则返回1(用于赋值给x),否则返回2(用于赋值给x)。
其他回答
如果不管输入数组中元素的顺序如何,你都想保证相同的顺序,这里是一个稳定排序:
myArray.sort(function(a, b) {
/* Storing case insensitive comparison */
var comparison = a.toLowerCase().localeCompare(b.toLowerCase());
/* If strings are equal in case insensitive comparison */
if (comparison === 0) {
/* Return case sensitive comparison instead */
return a.localeCompare(b);
}
/* Otherwise return result */
return comparison;
});
在(几乎:)一行代码中
["Foo", "bar"].sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
结果是
[ 'bar', 'Foo' ]
而
["Foo", "bar"].sort();
结果
[ 'Foo', 'bar' ]
myArray.sort(
function(a, b) {
if (a.toLowerCase() < b.toLowerCase()) return -1;
if (a.toLowerCase() > b.toLowerCase()) return 1;
return 0;
}
);
编辑: 请注意,我最初写这篇文章是为了说明技术,而不是考虑性能。也请参考回答@Ivan Krechetov更紧凑的解决方案。
arr.sort(function(a,b) {
a = a.toLowerCase();
b = b.toLowerCase();
if (a == b) return 0;
if (a > b) return 1;
return -1;
});
其他答案假设数组包含字符串。我的方法更好,因为即使数组包含null、undefined或其他非字符串,它也能工作。
var notdefined;
var myarray = ['a', 'c', null, notdefined, 'nulk', 'BYE', 'nulm'];
myarray.sort(ignoreCase);
alert(JSON.stringify(myarray)); // show the result
function ignoreCase(a,b) {
return (''+a).toUpperCase() < (''+b).toUpperCase() ? -1 : 1;
}
null将在'nulk'和'nulm'之间排序。但未定义的总是排在最后。