我有以下数组:
let arr = [
{"id": 123, "lastUpdate": 1543229793},
{"id": 456, "lastUpdate": 1545269320},
{"id": 123, "lastUpdate": 1552184795}
]
我需要根据相同的 ID 过滤数组,还要检查“lastUpdate”时间戳并只保留较新的条目。结果应该是:
[
{"id": 456, "lastUpdate": 1545269320},
{"id": 123, "lastUpdate": 1552184795}
]
我尝试了以下方法:
arr = arr.filter((e, index, self) =>
index === self.findIndex((t) => (
t.id === intent.id && t.lastUpdate > e.lastUpdate
))
)
但是,这为我过滤了所有内容,结果数组为空。我认为上面 && t.lastUpdate > e.lastUpdate
的最后一部分有问题。
非常感谢任何提示!
最佳答案
你好,如果你正在寻找一个高性能的解决方案,你可以使用一个对象:)
let arr = [{"id": 123,"lastUpdate": 1543229793},
{"id": 456,"lastUpdate": 1545269320},
{"id": 123, "lastUpdate": 1552184795}];
let newArr = {}
arr.forEach(el => {
if(!newArr[el.id] || newArr[el.id].lastUpdate < el.lastUpdate){
newArr[el.id] = el
}
})
console.log(Object.values(newArr));
关于javascript - 根据时间戳条件过滤数组中的唯一对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54366771/