首页 > 解决方案 > 在 JavaScript 中有一种方法可以对多维数组中的元素进行求和,并根据数组中的其他元素分组

问题描述

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

[
    [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 个元素添加到临时计数器,然后将结果推送到结果数组,有没有办法将这些分组并同时添加?

标签: javascriptarrays

解决方案


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

要解决您的问题,您需要进行最后 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],
]

目前,组键的类型是字符串,您可以将其转换为数字,如果需要,但我没有...


推荐阅读