陣列多重排序

看風景就發表於2017-11-26

寫法1

//直接在sort函式中自定義書寫,適用性強
array.sort(function(ob1,ob2) {
    if (ob1.strength > ob2.strength) {
        return 1;
    } else if (ob1.strength < ob2.strength) { 
        return -1;
    }
    // 當strength相等的時候會以name來進行比較
    if (ob1.name < ob2.name) { 
        return -1;
    } else if (ob1.name > ob2.name) {
        return 1
    } else { // nothing to split them
        return 0;
    }
})

寫法2

//比較使用一個通用函式,未必適用所有情況,字串可以使用>比較,比較的是其字典序
cmp = function(a, b) {
    if (a > b) return +1;
    if (a < b) return -1;
    return 0;
}
//直接使用原生的sort函式,當前面的比較為0時候,使用後面的比較
array.sort(function(a, b) { 
    return cmp(a.strength,b.strength) || cmp(a.name,b.name)
})

寫法3

//localeCompare比較會使用當地的字母比較規則,區別與>的unicode字典序
objects.sort(function (a, b) {
    return a.strength - b.strength || a.name.localeCompare(b.name);
});

寫法4

使用thenBy.js

 

 

出處: https://stackoverflow.com/questions/9175268/javascript-sort-function-sort-by-first-then-by-second

相關文章