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


当前回答

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

// Array.sortIgnoreCase() polyfill
if (!Array.prototype.sortIgnoreCase) {
    Array.prototype.sortIgnoreCase = function () {
        return this.sort(function (a, b) {
            return a.toLowerCase().localeCompare(b.toLowerCase());
        });
    };
}

其他回答

ES6版本:

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

来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator/compare

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

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

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

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

// Array.sortIgnoreCase() polyfill
if (!Array.prototype.sortIgnoreCase) {
    Array.prototype.sortIgnoreCase = function () {
        return this.sort(function (a, b) {
            return a.toLowerCase().localeCompare(b.toLowerCase());
        });
    };
}

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