gpt4 book ai didi

javascript - Lodash:使用最新项目创建新数组

转载 作者:行者123 更新时间:2023-12-02 16:25:01 26 4
gpt4 key购买 nike

我有一个如下的数组

[{
"id": "001",
"name": "A",
"timestamp_created": "2019-02-27T11:22:19"
},
{
"id": "002",
"name": "A",
"timestamp_created": "2019-02-27T11:30:19"
},
{
"id": "003",
"name": "B",
"timestamp_created": "2019-02-27T10:15:19"
},
{
"id": "004",
"name": "B",
"timestamp_created": "2019-02-27T11:05:19"
}
]

我想基于上述数组创建一个新数组,但仅包含最新项目(按项目名称分组)。

 [{
"id": "002",
"name": "A",
"timestamp_created": "2019-02-27T11:30:19"
},
{
"id": "004",
"name": "B",
"timestamp_created": "2019-02-27T11:05:19"
}
]

如何结合不同Lodash的功能来实现结果?

有什么建议,请帮助我。

最佳答案

你可以采取Map ,收集所有最新项目(通过检查 timestamp_created),按 name 分组并获取值。

var data = [{ id: "002", name: "A", timestamp_created: "2019-02-27T11:30:19" }, { id: "003", name: "B", timestamp_created: "2019-02-27T10:15:19" }, { id: "004", name: "B", timestamp_created: "2019-02-27T11:05:19" }, { id: "001", name: "A", timestamp_created: "2019-02-27T11:22:19" }],
result = Array.from(data
.reduce(
(m, o) => m.has(o.name) && m.get(o.name).timestamp_created > o.timestamp_created
? m
: m.set(o.name, o),
new Map
)
.values()
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - Lodash:使用最新项目创建新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54908753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com