gpt4 book ai didi

javascript - 如何有效地对对象进行分组并为每组对象进行计算

转载 作者:行者123 更新时间:2023-11-29 15:58:19 32 4
gpt4 key购买 nike

我正在开发一个 javascript 应用程序,我从 API 获取一些数据,这是数据集的一些记录的样子:

    {eventAction: "area", sessionId: "20190515|04434531", timestamp: "15- 
05-2019 10:56:28", duration: "45.665", nodeId: "1", …}
{eventAction: "area", sessionId: "20190515|04434531", timestamp: "15-
05-2019 10:56:28", duration: "47.602", nodeId: "9", …}
{eventAction: "area", sessionId: "20190515|04434531", timestamp: "15-
05-2019 10:56:28", duration: "5.287", nodeId: "12", …}
{eventAction: "area", sessionId: "20190515|04434531", timestamp: "15-
05-2019 10:56:28", duration: "5.932", nodeId: "27", …}
{eventAction: "area", sessionId: "20190515|04434531", timestamp: "15-
05-2019 10:56:28", duration: "56.918", nodeId: "9", …}

如您所见,这是一组对象,现在我要做的是,将这组对象按 nodeId 分组。所以我可以对每个 nodeId 进行计算。我想要每个 nodeId 的平均持续时间。但我真的不知道从哪里开始/如何有效地做到这一点。

我认为它必须与一些过滤器/ map /归约一起使用,对吗?我还不能完全理解这个问题

谢谢你的问候

最佳答案

您可以获取一个对象并存储每个 nodeId 的总和、计数和平均值。

var data = [{ eventAction: "area", sessionId: "20190515|04434531", timestamp: "15-05-2019 10:56:28", duration: "45.665", nodeId: "1" }, { eventAction: "area", sessionId: "20190515|04434531", timestamp: "15-05-2019 10:56:28", duration: "47.602", nodeId: "9" }, { eventAction: "area", sessionId: "20190515|04434531", timestamp: "15-05-2019 10:56:28", duration: "5.287", nodeId: "12" }, { eventAction: "area", sessionId: "20190515|04434531", timestamp: "15-05-2019 10:56:28", duration: "5.932", nodeId: "27" }, { eventAction: "area", sessionId: "20190515|04434531", timestamp: "15-05-2019 10: 56: 28", duration: "56.918", nodeId: "9" }],
result = data.reduce((r, { duration, nodeId }) => {
r[nodeId] = r[nodeId] || { sum: 0, count: 0, average: 0 };
r[nodeId].sum += +duration;
r[nodeId].average = r[nodeId].sum / ++r[nodeId].count;
return r;
}, {});

console.log(result)

关于javascript - 如何有效地对对象进行分组并为每组对象进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56147639/

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