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

标签 javascript arrays object javascript-objects lodash

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

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/

相关文章:

javascript - 使用 Jquery 向表单提交的 URL 添加值

javascript string.替换任何语言

arrays - 如何根据一列元素的频率对矩阵的行进行排序?

javascript - 为 JavaScript 中的每个列表项遍历数组

javascript - 如何在javascript中设置传递的函数

c++ - 为什么在没有明显代码的情况下删除对象?

delphi - 怎样才能实现免费的Interface类呢?

javascript - 如何将函数的结果添加到另一个函数并使用 java 在 DIV ID html 中显示

javascript - 如何返回对象的所有属性及其值,包括可迭代的、自定义的和继承的?

c# - 在 C# 中安全/惯用地提取子数组