You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现按timestamp分组计算数组中对应useful value的总和?

计算分组后每个timestamp的useful value总和

情况1:分组结果为数组(每个元素包含timestamp和对应value列表)

假设你的分组后数组结构如下:

const groupedArray = [
  { timestamp: 162344684165, usefulValues: [8, 8] },
  { timestamp: 162344743456, usefulValues: [6, 6] },
  // 更多分组项
];

方法1:使用reduce链式调用

const sumResult = groupedArray.reduce((acc, current) => {
  // 对当前分组的usefulValues求和
  const total = current.usefulValues.reduce((sum, val) => sum + val, 0);
  acc[current.timestamp] = total;
  return acc;
}, {});

方法2:使用forEach循环(更易读)

const sumResult = {};
groupedArray.forEach(item => {
  let total = 0;
  item.usefulValues.forEach(val => total += val);
  sumResult[item.timestamp] = total;
});

情况2:分组结果为对象(键为timestamp,值为对应value数组)

如果你的分组结果是类似这样的对象:

const groupedObj = {
  162344684165: [5, 11],
  162344743456: [7, 5],
  // 更多键值对
};

方法1:结合Object.entries和reduce

const sumResult = Object.entries(groupedObj).reduce((acc, [timestamp, values]) => {
  acc[timestamp] = values.reduce((sum, val) => sum + val, 0);
  return acc;
}, {});

方法2:forEach遍历键值对

const sumResult = {};
Object.entries(groupedObj).forEach(([timestamp, values]) => {
  let total = 0;
  values.forEach(val => total += val);
  sumResult[timestamp] = total;
});

注意事项

如果你的useful value是字符串类型(比如从接口返回的字符串数字),需要先转换为数字再求和,避免字符串拼接:

total += Number(val);
// 或者用parseInt/parseFloat,根据实际数值类型选择

内容的提问来源于stack exchange,提问作者Stephen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:10:55