gpt4 book ai didi

javascript - 基于一些计算将复杂的 javascript 数组减少到另一个数组?

转载 作者:行者123 更新时间:2023-12-03 07:18:45 27 4
gpt4 key购买 nike

我有一个对象数组

data: [
{
eventId: "EVEN00001",
eventType: "call",
startDate: "2018-08-01T21:30:17+05:30",
},
{
eventId: "EVEN00002",
eventType: "call",
startDate: "2018-08-01T21:30:17+05:30",
},
{
eventId: "EVEN00003",
eventType: "meeting",
startDate: "2017-02-03T21:30:17+05:30",
},
{
eventId: "EVEN00004",
eventType: "email",
startDate: "2018-09-04T21:30:17+05:30",
},
{
eventId: "EVEN00005",
eventType: "meeting",
startDate: "2018-09-05T21:30:17+05:30",
}]

我想把它减少到

[{call: 2},{meeting: 2},{email: 1}]

如何使用 javascript reduce 方法实现此目的,不知何故,我能够达到预期的结果,但这不是正确的方法。

data.reduce((acc, item, i, arr) => {
if (!acc[item.startDate]) {
acc[item.startDate] = 1;
} else {
acc[item.startDate] += 1;
}
return acc;
}, {});
const dayArray = Object.entries(trimedData)
.reduce((acc, node, i, arr) => {

let [days, val] = node;
acc.push({
days: days,
value: val
})
return acc;
}, []);

如何仅使用 reduce. 或任何其他更好的方法来达到预期的结果?

最佳答案

reduce 为由 eventType 索引的对象,其值为该 eventType 到目前为止出现的次数 - 将适当的属性增加每次迭代一个。然后,获取该对象的值:

const data=[{eventId:"EVEN00001",eventType:"call",startDate:"2018-08-01T21:30:17+05:30",},{eventId:"EVEN00002",eventType:"call",startDate:"2018-08-01T21:30:17+05:30",},{eventId:"EVEN00003",eventType:"meeting",startDate:"2017-02-03T21:30:17+05:30",},{eventId:"EVEN00004",eventType:"email",startDate:"2018-09-04T21:30:17+05:30",},{eventId:"EVEN00005",eventType:"meeting",startDate:"2018-09-05T21:30:17+05:30",}]

console.log(Object.values(
data.reduce((a, { eventType }) => {
if (!a[eventType]) a[eventType] = { [eventType] : 0 };
a[eventType][eventType]++;
return a;
}, {})
));

关于javascript - 基于一些计算将复杂的 javascript 数组减少到另一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52913109/

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