猿问

Javascript 按 2 个属性排序和筛选数组

我想按日期保留最高分列表:



姓名:玩家 A |成绩: 2000 |日期: 2020-04-15


姓名:球员B|成绩: 2001 |日期: 2020-04-16


但是,我有时会得到更高的分数,但日期更低:


姓名:球员A|成绩: 2000 |日期: 2020-01-12


姓名:球员B|成绩: 2001 |日期: 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)


不负相思意
浏览 89回答 2
2回答

手掌心

只需在排序时输入这两个条件:<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>

慕斯王

filter 方法提供三个参数:当前元素当前元素的索引数组因此,您尝试将提交的与未定义进行比较。如果需要从排序数组中获取两个元素,则可以使用拼接方法arr.sort((a,&nbsp;b)&nbsp;=>&nbsp;b.score&nbsp;-&nbsp;a.score).splice(0,&nbsp;2)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答