我有一个数组数组,每个嵌套数组都包含一个具有 2 个值的对象:好 和 坏。
[
0:[
count:{
good: 5,
bad: 3
}
],
1:[
count:{
good: 7,
bad: 6
}
],
2:[
count:{
good: 0,
bad: 8
}
],
3:[
count:{
good: 0,
bad: 9
}
],
4:[
count:{
good: 4,
bad: 1
}
]
]
我想按 good 从高到低对数组进行排序,然后当 good 为 0 时,将其余数组按降序排列从高到低按坏排序。所以生成的数组将如下所示:
[
0:[
count:{
good: 7,
bad: 6
}
],
1:[
count:{
good: 5,
bad: 3
}
],
2:[
count:{
good: 4,
bad: 1
}
],
3:[
count:{
good: 0,
bad: 9
}
],
4:[
count:{
good: 0,
bad: 8
}
]
]
我正在使用 Underscore,但对于如何最好地处理这个问题有点困惑,因为我想根据两个值进行排序,并且它们位于嵌套数组内的对象内。 p>
使用 sortBy 似乎是显而易见的选择,但我不确定如何首先按好排序,然后按坏排序。
sortBy
_.sortBy(list, iterator, [context])
Returns a sorted copy of list, ranked in ascending order by the results of running each value through iterator. Iterator may also be the string name of the property to sort by (eg.
length
).
最佳答案
如果有合适的数组,您可以使用 Array#sort
使用自定义回调。
var array = [{ count: { good: 5, bad: 3 } }, { count: { good: 7, bad: 6 } }, { count: { good: 0, bad: 8 } }, { count: { good: 0, bad: 9 } }, { count: { good: 4, bad: 1 } }];
array.sort(function (a, b) {
return b.count.good - a.count.good || b.count.bad - a.count.bad;
});
console.log(array);
关于javascript - 按一个值对嵌套数组排序,然后按另一个值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37965757/