【问题标题】:In JavaScript is there a way to sum elements in multi-dimensional arrays, grouped on other elements in the array在 JavaScript 中,有一种方法可以对多维数组中的元素进行求和,并根据数组中的其他元素分组
【发布时间】:2021-04-08 21:37:27
【问题描述】:

我正在使用如下所示的多维数组

[
    [203, 541, 5001, 6.8, 207, 30252], 
    [203, 542, 5001, 16.3, 83, 50832], 
    [203, 542, 5001, 60.9, 207, 30252],
    [203, 542, 5003, null, 207, 30252],
    [203, 541, 5001, 15, 965, 52452],
    [203, 542, 5003, 6.8,207, 30252],
    [203, 542, 5003, null, 207, 30252],
    [203, 541, 5001, 15, 965, 52452],
    [203, 542, 5003, 6.8,207, 30252]
]

前 3 个元素是 ID 整数,后 3 个元素是浮点数。我试图能够根据前 3 个元素对这些元素进行分组并(单独)添加计数,因此我将以如下所示的数组结尾

[
    [203, 541, 5001, 36.8, 1937, 30252], // Sum the last 3 elements that have 203,541,5001 as the beginning 3 elements of the array
    [203, 542, 5001, 77.2, 290, 81084], // Sum the last 3 elements that have 203,541, 5001 as the beginning 3 elements of the array
    [203, 541, 5003, a, b, c], // same as above
    [203, 542, 5003, x, y, z] // same as above
]

如果不循环遍历所有数组,创建临时计数器,然后循环遍历每个数组元素以将最后 3 个元素添加到临时计数器,然后将结果推送到结果数组,有没有办法将这些分组并添加到同一时间?

【问题讨论】:

  • 到目前为止你得到了什么代码?
  • 基本上循环遍历数组,创建临时计数器(作为前 3 个元素),循环遍历每个内部数组,并添加到临时计数器,想知道是否有更好的方法来做到这一点

标签: javascript arrays


【解决方案1】:

我假设您尝试了任何代码实现来解决您的问题。无论如何,这是我的答案...

要解决你的问题,你需要做最后2个操作,分组和修改。

const data = [
    [203, 541, 5001, 6.8, 207, 30252],
    [203, 542, 5001, 16.3, 83, 50832],
    [203, 542, 5001, 60.9, 207, 30252],
    [203, 542, 5003, null, 207, 30252],
    [203, 541, 5001, 15, 965, 52452],
    [203, 542, 5003, 6.8, 207, 30252],
    [203, 542, 5003, null, 207, 30252],
    [203, 541, 5001, 15, 965, 52452],
    [203, 542, 5003, 6.8, 207, 30252]
];
function group(data) {
    let group = new Map;
    let result = [];
    for (let entry of data) {
        // You can comment this line, If you don't need `data`.
        entry = [...entry]; // Cloning, Don't want to modify `data` directly...
        const key = entry.splice(0, 3).join(',');
        const item = group.get(key);
        if (!item) group.set(key, entry)
        else for (let i = 0; i < entry.length; i++) {
            item[i] += entry[i];
        }
    }
    for (const [key, value] of group) {
        result.push(key.split(',').concat(value));
    }
    return result;
}
console.log(group(data));

结果:

[
    ["203", "541", "5001", 36.8, 2137, 135156],
    ["203", "542", "5001", 77.2, 290, 81084],
    ["203", "542", "5003", 13.6, 828, 121008],
]

目前group key的类型是string,你可以转成number,如果你愿意,但是我没有...

【讨论】:

  • 谢谢,我基本上做了同样的事情,但是,我最初并没有使用 Map 对象,而是改为使用它来提高获取和设置的效率。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多