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


当前回答

如果不管输入数组中元素的顺序如何,你都想保证相同的顺序,这里是一个稳定排序:

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;
});

其他回答

用. tolowercase()规范.sort()中的case。

你也可以使用新的Intl.Collator().compare,每个MDN在排序数组时更有效。缺点是旧的浏览器不支持它。MDN声明Safari根本不支持它。需要验证它,因为它声明Intl。支持Collator。

当比较大量字符串时,例如对大型数组排序时,最好创建Intl。对象,并使用其compare属性提供的函数

["Foo", "bar"].sort(Intl.Collator().compare); //["bar", "Foo"]

在/ /i中包装字符串。这是使用正则表达式忽略大小写的一种简单方法

其他答案假设数组包含字符串。我的方法更好,因为即使数组包含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'之间排序。但未定义的总是排在最后。

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