我有一个字符串数组,我需要在JavaScript中排序,但以不区分大小写的方式。如何做到这一点?


当前回答

现在是时候重新审视这个老问题了。

您不应该使用依赖toLowerCase的解决方案。它们效率很低,而且在某些语言(例如土耳其语)中根本不起作用。喜欢这个:

['Foo', 'bar'].sort((a, b) => a.localeCompare(b, undefined, {sensitivity: 'base'}))

查看浏览器兼容性文档,了解灵敏度选项的所有信息。

其他回答

在(几乎:)一行代码中

["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更紧凑的解决方案。

你也可以使用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)。

arr.sort(function(a,b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    if (a == b) return 0;
    if (a > b) return 1;
    return -1;
});

如果你在努力理解以下内容,这可能会有所帮助:

var array = ["sort", "Me", "alphabetically", "But", "Ignore", "case"];
console.log('Unordered array ---', array, '------------');

array.sort(function(a,b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    console.log("Compare '" + a + "' and '" + b + "'");

    if( a == b) {
        console.log('Comparison result, 0 --- leave as is ');
        return 0;
    }
    if( a > b) {
        console.log('Comparison result, 1 --- move '+b+' to before '+a+' ');
        return 1;
    }
    console.log('Comparison result, -1 --- move '+a+' to before '+b+' ');
    return -1;


});

console.log('Ordered array ---', array, '------------');


// return logic

/***
If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
***/

http://jsfiddle.net/ianjamieson/wmxn2ram/1/