数组对象排序,先根据某个属性排序,然后再此基础上根据另外一个属性值排序,不会打乱第一个排序【先根据年份,再根据月份】
// 排序,先进行某个对象属性排序,然后在此基础上进行另一个属性排序[先按年份,再按月份] export function multisort(array, ...compairers) { return array.sort((a, b) => { for (const c of compairers) { const r = c(a, b); if (r !== 0) { return r; } } }); }
var aee = [
{"key":{"Year":2019,"Month":1},"sum":1},
{"key":{"Year":2018,"Month":1},"sum":2},
{"key":{"Year":2019,"Month":6},"sum":1},
{"key":{"Year":2018,"Month":4},"sum":1},
{"key":{"Year":2019,"Month":2},"sum":2}
] console.log(aee); function multisort(array, ...compairers) { return array.sort((a, b) => { for (const c of compairers) { const r = c(a, b); if (r !== 0) { return r; } } }); } multisort(aee,(a, b) => b.key.Year - a.key.Year, (a, b) => b.key.Month - a.key.Month)
//
结果
[{"key":{"Year":2019,"Month":6},"sum":1}, {"key":{"Year":2019,"Month":2},"sum":2}, {"key":{"Year":2019,"Month":1},"sum":1}, {"key":{"Year":2018,"Month":4},"sum":1}, {"key":{"Year":2018,"Month":1},"sum":2}]