这里有一个函数,您可以使用它按多个对象对列表进行排序,如果第一个对象相等,则第二个顺序将用作回退。如果可能的话,空值也应忽略到回退顺序。
function sortObjects(list, orderBy){
list.sort(function(a, b){
let byIndex = 0;
let order = orderBy[byIndex];
while(!a[order.by] || !b[order.by] || a[order.by] === b[order.by]){
byIndex++;
if(byIndex >= orderBy.length){break;}
order = orderBy[byIndex];
}
if(!a[order.by] || !b[order.by] || a[order.by] === b[order.by]){
return false;
}
if(order.desc){
return a[order.by] < b[order.by];
}
return a[order.by] > b[order.by];
});
return list;
}
用法:
var objs = [
{a: 10, b: 20, c: 30},
{a: 30, b: 10, c: 20},
{a: 20, b: 10, c: 30},
];
sortObjectList(objs, [{by: 'a'}]);
[
{a: 10, b: 20, c: 30},
{a: 20, b: 10, c: 30},
{a: 30, b: 10, c: 20},
]
sortObjectList(objs, [{by: 'a', desc: true}]);
[
{a: 30, b: 10, c: 20},
{a: 20, b: 10, c: 30},
{a: 10, b: 20, c: 30},
]
sortObjectList(objs, [{by: 'b', desc: true}, {by: 'c'}]);
[
{a: 10, b: 20, c: 30},
{a: 30, b: 10, c: 20},
{a: 20, b: 10, c: 30},
]
另一个例子:
var objs = [
{a: 5, b: 5},
{a: 10, b: 15},
{a: 15, b: 25},
{b: 10},
{b: 20},
{a: 10, b: 30},
{a: 10, b: 12},
];
sortObjectList(objs, [{by: 'a'}, {by: 'b'}]);
[
{a: 5, b: 5},
{b: 10},
{a: 10, b: 12},
{a: 10, b: 15},
{b: 20},
{a: 10, b: 30},
{a: 15, b: 25},
]