根据两个条件减少javascript中的数组[关闭]
Posted
技术标签:
【中文标题】根据两个条件减少javascript中的数组[关闭]【英文标题】:Reduce array in javascript based on two conditions [closed] 【发布时间】:2022-01-06 06:05:04 【问题描述】:假设我们有一个对象数组,例如:
[
id: 1, time: "2021-05-02 10:12:45.123" ,
id: 1, time: "2021-05-02 11:12:45.123" ,
id: 1, time: "2021-05-02 12:12:45.123" ,
id: 2, time: "2021-05-02 05:12:45.123" ,
id: 1, time: "2021-05-01 12:12:45.123" ,
id: 2, time: "2021-05-01 05:12:45.123" ,
id: 2, time: "2021-05-01 04:12:45.123" ,
id: 3, time: "2021-05-01 10:12:45.123" ,
]
所以我的目的是减少 javascript 中的数组,因此结果是 -> 每天的每个 Id 都有最新的时间,例如:
[
id: 1, time: "2021-05-02 12:12:45.123" ,
id: 2, time: "2021-05-02 05:12:45.123" ,
id: 1, time: "2021-05-01 12:12:45.123" ,
id: 2, time: "2021-05-01 05:12:45.123" ,
id: 3, time: "2021-05-01 10:12:45.123" ,
]
请你帮忙。提前致谢
【问题讨论】:
【参考方案1】:您可以使用reduce
轻松实现结果
const arr = [
id: 1, time: "2021-05-02 10:12:45.123" ,
id: 1, time: "2021-05-02 11:12:45.123" ,
id: 1, time: "2021-05-02 12:12:45.123" ,
id: 2, time: "2021-05-02 05:12:45.123" ,
id: 1, time: "2021-05-01 12:12:45.123" ,
id: 2, time: "2021-05-01 05:12:45.123" ,
id: 2, time: "2021-05-01 04:12:45.123" ,
id: 3, time: "2021-05-01 10:12:45.123" ,
];
const result = arr.reduce((acc, curr) =>
if (acc.length && acc[acc.length - 1].id === curr.id)
if (new Date(acc[acc.length - 1].time) < new Date(curr.time))
acc[acc.length - 1] = ...acc[acc.length - 1], ...curr ;
else acc.push(curr);
return acc;
, []);
console.log(result);
【讨论】:
以上是关于根据两个条件减少javascript中的数组[关闭]的主要内容,如果未能解决你的问题,请参考以下文章
如何在javascript中将对象数组过滤为另一个对象数组? [关闭]
如何根据javascript中的键合并和替换两个数组中的对象?