迭代多维数组并基于第一个索引返回汇总和 [英] Iterate over multi-dimensional array and return aggregated sum based on first index

查看:37
本文介绍了迭代多维数组并基于第一个索引返回汇总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很伤脑筋,为此提供的任何帮助都将不胜感激.我目前有一个对象数组,每个对象都有两个属性,一个时间戳(自纪元以来的毫秒数)和该时间戳的任意属性.像这样:

I've really been wrecking my brain over this one so any assistance is greatly appreciated. I currently have an array of objects and each of these objects has two properties, a timestamp (ms since epoch) and an arbitrary for that timestamp. Like so:

[
    [1518739200000, 1], 
    [1518739200000, 1],
    [1518739200000, 12],
    [1518739200000, 16],
    [1518739200000, 16],
    [1518825600000, 16],
    [1518825600000, 20],
    [1518825600000, 20],
    [1518825600000, 8],
]

我要做的是将多维数组压缩为另一个多维数组,该多维数组仅具有第一个索引的唯一值,时间戳和一个聚合计数作为第二个值.例如,我正在从上面提供的给定数据集中寻找这一点.

What I'm trying to do is to condense the multidimensional array into another multidimensional array which has only the unique values of the first index, the timestamp, and an aggregate count as the second value. In example, I'm looking for this from the given set of data included above.

[
    [1518739200000, 46],
    [1518825600000, 64],
]

我已经尝试了几种使用.reduce的方法,但对于这种特殊的类型的操作尚未获得任何成功.

I've tried using .reduce in a few ways but haven't had any success yet for this particular kind manipulation.

推荐答案

使用功能 reduce

let array = [[1518739200000, 1], [1518739200000, 1],[1518739200000, 12],[1518739200000, 16],[1518739200000, 16],[1518825600000, 16],[1518825600000, 20],[1518825600000, 20],[1518825600000, 8]];
let result = Object.values(array.reduce((a, [key, value]) => {
  (a[key] || (a[key] = [key, 0]))[1] += value;
  return a;
}, {}));

console.log(result);

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

这篇关于迭代多维数组并基于第一个索引返回汇总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆