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

标签 javascript arrays underscore.js

我有一个数组数组,每个嵌套数组都包含一个具有 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/

相关文章:

javascript - 在 Marionette/underscore 模板中使用带有奇怪字符的属性

javascript - 将属性添加到对象数组

Javascript 将时区 MESZ 的日期转换为 NaN

javascript - 检查元素是否是 DOM 中类的最后一个

javascript - amCharts 不显示最初隐藏的 div 的图表

javascript - forEach 在客户端具有单文档 firebase 查询?

javascript - 如何在 Astra DB 中使用类似 JSON 的数据以及矢量搜索

arrays - 使用 excel vba 通过分隔符分割字符串同时忽略所述分隔符的某些实例的最有效方法

php - in_array 组合值 ('test' ,'value' )

javascript - 如何制作 `where not` 大小写?