按字母顺序排序,然后按大小写

时间:2017-01-15 07:24:51

标签: javascript arrays sorting

我将如何按字母顺序对字符串数组进行排序,然后按案例排序。

示例输入:

var myObj = {"name": true, "Updated Date": false}

var myPredicates = [];

for(var prop in myObj) {
    myPredicates.push('"\'' + prop + '\'"');
}

console.log(myPredicates[0]);
console.log(myPredicates[1]);

期望的输出:

    ["A","d","B","a","D","c","C","b"]

3 个答案:

答案 0 :(得分:0)

你会使用带有回调函数的Array#sort,首先比较不区分大小写的情况,然后如果第一次比较被认为是相等则区分大小写

["A","d","B","a","D","c","C","b"].sort(function (A, B) {
    var a = A.toLowerCase(), b = B.toLowerCase();
    if (a < b) {
        return -1;
    } else if (a > b) {
        return 1;
    } else if (A < B) {
        return -1;
    } else if (A > B) {
        return 1;
    } else {
        return 0;
    }
});

答案 1 :(得分:0)

这是一个单行,可能效率低于Jaromanda的版本,但代码较少:

["A","d","B","a","D","c","C","b"].sort((a, b) => String.localeCompare(...(a.toLowerCase() == b.toLowerCase() ? [b, a] : [a.toLowerCase(), b.toLowerCase()])))

答案 2 :(得分:0)

您可以先比较小写字母,然后再移动大写字母值。

&#13;
&#13;
var array = ["A", "d", "B", "a", "D", "c", "C", "b"];

array.sort(function (a, b) {
    var aa = a.toLowerCase(),
        bb = b.toLowerCase();

    return aa.localeCompare(bb) || (a === aa) - (b === bb) ;
});

console.log(array);
&#13;
&#13;
&#13;