gpt4 book ai didi

javascript - 基于两个条件的过滤数组

转载 作者:行者123 更新时间:2023-11-28 05:55:49 24 4
gpt4 key购买 nike

我有以下对象数组,(表示这里的时间温度是模拟的,更大的是最后一个)

var firstArr = [{
id: 1,
a: 2,
timestemp: 111
}, {
id: 2,
a: 4,
timestemp: 222
}, {
id: 3,
a: 6,
timestemp: 333
}, {
id: 1,
a: 3,
timestemp: 777
}, {
id: 3,
a: 5555,
timestemp: 5555
}];

我需要做的是以某种方式过滤这个数组并创建具有唯一值的新数组。

我需要在最后

var endArr = [{
id: 1,
a: 3,
timestemp: 777
}, {
id: 2,
a: 4,
timestemp: 222
}, {
id: 3,
a: 5555,
timestemp: 555
}];

正如你所看到的,我已经通过两件事过滤了这个数组

  1. uniqe ID (the entry 1 & 3 are exist just once)
  2. timestemp (add just the object with the last timestemp)

如何使用诸如map/reduce/filter之类的数组方法来做到这一点?

我尝试使用 array.filter 执行此操作,但没有成功

最佳答案

您可以使用orderBy()uniqBy()获取具有最新时间戳的唯一 ID 的所有项目:

var firstArr = [{
id: 1,
a: 2,
timestamp: 111
}, {
id: 2,
a: 4,
timestamp: 222
}, {
id: 3,
a: 6,
timestamp: 333
}, {
id: 1,
a: 3,
timestamp: 777
}, {
id: 3,
a: 5555,
timestamp: 5555
}];

var result = _(firstArr)
.orderBy(['id', 'timestamp'], ['asc', 'desc'])
.uniqBy('id')
.value();

console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

关于javascript - 基于两个条件的过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37700106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com