我有以下对象数组,(表示这里的时间温度是模拟的,更大的是最后一个)
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
}];
正如你所看到的,我已经通过两件事过滤了这个数组
- uniqe ID (the entry 1 & 3 are exist just once)
- 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/