條件排序

var items = [
    {name: "linc", age: 28, num: 12345},
    {name: "linc", age: 28, num: 1234},
    {name: "kiki", age: 20, num: 12345},
    {name: "高峯", age: 26, num: 123},
    {name: "高峯", age: 27, num: 101},
    {name: "高峯", age: 26, num: 111},
    {name: "安迪", age: 29, num: 110},
    {name: "安迪", age: 30, num: 110}
];


// ascending 升序  descending 降序
(function _default() {
    items.sort(function (a, b) {
        return SortByProps(a, b, ['name', 'age', 'num'], {name: 'ascending', age: 'descending'});
    });
    console.log(items)
})();

function SortByProps(item1, item2, attr, obj) {
    /**
     * @type {Array}
     * attr: Array 按照數組的順序排序
     * obj: { attr[index]: 'ascending'/ 'descending' } ascending '升序' descending '降序'
     */
    var props = [];
    if (obj) {
        props.push(obj)
    }
    var cps = []; // 存儲排序屬性比較結果。
    // 若是未指定排序屬性(即obj不存在),則按照全屬性升序排序。
    // 記錄下兩個排序項按照各個排序屬性進行比較獲得的結果
    var asc = true; // 記錄升序仍是降序,升序 true  降序 false
    if (props.length < 1) {
        for (var p of attr) {
            if (item1[p] > item2[p]) {
                cps.push(1);
                break; // 大於時跳出循環。
            } else if (item1[p] === item2[p]) {
                cps.push(0);
            } else {
                cps.push(-1);
                break; // 小於時跳出循環。
            }
        }
    }
    else {
        for (var i = 0; i < props.length; i++) {
            var prop = props[i];
            for (var o of attr) {
                prop[o] ? asc = (prop[o] === "ascending") : asc = true;
                if (item1[o] > item2[o]) {
                    cps.push(asc ? 1 : -1);
                    break; // 大於時跳出循環。
                } else if (item1[o] === item2[o]) {
                    cps.push(0);
                } else {
                    cps.push(asc ? -1 : 1);
                    break; // 小於時跳出循環。
                }
            }
        }
    }
    return cps[cps.length - 1]
}
相關文章
相關標籤/搜索