[英]Javascript sort and filter array by 2 properties
I want to keep a list of the highest scores by date:我想按日期保留最高分数的列表:
ie IE
Name: Player A |姓名:玩家A | Score: 2000 |
得分:2000 | Date: 2020-04-15
日期:2020-04-15
Name: Player B|姓名:玩家B| Score: 2001 |
得分:2001 | Date: 2020-04-16
日期:2020-04-16
However i sometimes get a greater score but lower date:然而,我有时会得到更高的分数但更低的日期:
Name: Player A|姓名:玩家A| Score: 2000 |
得分:2000 | Date: 2020-01-12
日期: 2020-01-12
Name: Player B|姓名:玩家B| Score: 2001 |
得分:2001 | Date: 2019-12-20
日期: 2019-12-20
// should only return: a and c in order.
let arr = [
{name: c, score: 6, date: 5-20-2021},
{name: b, score: 2, date: 5-20-2020},
{name: a, score: 3, date: 5-20-2019}
]
arr.sort((a, b) => (a.score > b.score) ? 1 : -1)
arr.filter((a, b) => (a.submitted > b.submitted) ? 1 : -1)
filter method provide three arguments:过滤方法提供三个arguments:
Therefore, you try to compare submitted with undefined.因此,您尝试将已提交与未定义进行比较。 If you need to get two element from a sorted array, you can just use splice method
如果您需要从排序数组中获取两个元素,您可以使用splice方法
arr.sort((a, b) => b.score - a.score).splice(0, 2)
Just put both conditions when you sort:排序时只需输入两个条件:
<script> let arr = [ {name: "i", score: 16, date: 2-20-2021}, {name: "h", score: 6, date: 5-25-2021}, {name: "g", score: 6, date: 5-20-2022}, {name: "f", score: 6, date: 5-10-2021}, {name: "e", score: 16, date: 5-20-1021}, {name: "d", score: 6, date: 5-20-2001}, {name: "c", score: 6, date: 5-20-2021}, {name: "b", score: 2, date: 5-20-2020}, {name: "a", score: 3, date: 5-20-2019} ] arr.sort((a, b) => (a.score < b.score) && (a.date < b.date)? 1: -1) console.log(arr) </script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.