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


当前回答

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

在上面的函数中,如果我们只比较小写的两个值a和b,我们将不会得到漂亮的结果。

例如,如果数组是[A, A, B, B, c, c, D, D, e, e],我们使用上面的函数,我们就得到了这个数组。它没有改变任何东西。

为了使结果为[A, A, B, B, C, C, D, D, E, E],当两个小写值相等时,我们应该再次进行比较:

function caseInsensitiveComparator(valueA, valueB) {
    var valueALowerCase = valueA.toLowerCase();
    var valueBLowerCase = valueB.toLowerCase();

    if (valueALowerCase < valueBLowerCase) {
        return -1;
    } else if (valueALowerCase > valueBLowerCase) {
        return 1;
    } else { //valueALowerCase === valueBLowerCase
        if (valueA < valueB) {
            return -1;
        } else if (valueA > valueB) {
            return 1;
        } else {
            return 0;
        }
    }
}

其他回答

我把上面的答案包装在一个填充中,这样我就可以在字符串数组上调用.sortIgnoreCase()

// Array.sortIgnoreCase() polyfill
if (!Array.prototype.sortIgnoreCase) {
    Array.prototype.sortIgnoreCase = function () {
        return this.sort(function (a, b) {
            return a.toLowerCase().localeCompare(b.toLowerCase());
        });
    };
}
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'之间排序。但未定义的总是排在最后。

在(几乎:)一行代码中

["Foo", "bar"].sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
});

结果是

[ 'bar', 'Foo' ]

["Foo", "bar"].sort();

结果

[ 'Foo', 'bar' ]

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

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

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