使用Angular 6中的时间戳,仅过滤对象中具有相同ID的最新数据 [英] Filter only the latest data for the same ID in an object, using timestamp in Angular 6
本文介绍了使用Angular 6中的时间戳,仅过滤对象中具有相同ID的最新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个存储在'component'变量中的对象数组
I have an array of objects stored in 'component' variable
component=[{id:1,date:'20-10-2020'},{id:1,date:'13-01-2020'},{id:2,date:'30-03-2020'}]
在这里,我有2个对象,它们的"id"相同(id:1),但日期不同.如果其中有多个具有相同ID的对象,我只需要取出具有最新日期的ID.可以使用过滤器吗?
Here I'm having 2 objects with 'id' as same(id:1) but with different dates. If there are multiple objects with the same id in it, I need to take out only the id with the latest date. Is it possible with filters?
过滤后,我需要输出类似
After filtering, I need the output like
component=[{id:1,date:'20-10-2020'},{id:2,date:'30-03-2020'}]
此处'{id:1,date:'13 -01-2020'}'已从阵列中删除.
Here '{id:1,date:'13-01-2020'}' is removed from the array.
预先感谢
推荐答案
您可以使用以下使用Map的代码来做到这一点:
You may do so using the following code which makes use of a Map:
let map = new Map();
component.forEach(e => {
if (map.get(e.id) !== undefined) {
// current date
const [newDay, newMonth, newYear] = e.date.split("-")
let newDate = new Date(newYear, newMonth - 1, newDay);
// previous date
const [oldDay, oldMonth, oldYear] = map.get(e.id).split("-")
let oldDate = new Date(oldYear, oldMonth - 1, oldDay);
// compare the date and pick the latest
map.set(e.id, newDate > oldDate ? e.date : map.get(e.id));
} else {
map.set(e.id, e.date);
}
});
// clear the original contents
component = [];
// now populate it from the map
for (let e of map.entries()) {
component.push({id: e[0], date: e[1]});
}
console.log(component);
这篇关于使用Angular 6中的时间戳,仅过滤对象中具有相同ID的最新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文