按一个值排序嵌套数组,然后按另一个值排序

Order nested arrays by one value, then another

我有一个数组数组,每个嵌套数组包含一个具有 2 个值的对象:goodbad.

[
    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,对于如何最好地解决这个问题有点困惑,因为我想根据两个值进行排序,它们 在嵌套数组中的一个对象中.

使用 sortBy 似乎是显而易见的选择,但我不确定如何先按 good 排序,然后再按 bad 排序.

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);

其实你的问题在你问之前就已经回答了。 here 是一种增强的方法。