Scott Miller
Scott Miller

Reputation: 332

In JavaScript is there a way to sum elements in multi-dimensional arrays, grouped on other elements in the array

I am working with a multi-dimensional array like below

[
    [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]
]

Where the first 3 elements are ID ints, and the last 3 are count floats. I am trying to be able to group these based on the first 3 elements and add the counts (individually) so I would end with an array like below

[
    [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
]

Without looping through all arrays, creating temp counters, then looping through each array element to add the last 3 elements to the temp counters and then pushing the result to a result array, is there a way to group these and add at the same time?

Upvotes: 1

Views: 76

Answers (1)

Nur
Nur

Reputation: 2473

I assume that you tried any code implementation to solve your problem. Anyway here is my answer...

To solve your problem you need to do at last 2 operation, group and modify.

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));

Result:

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

Currently, type of group key is string, You can convert it to number, If you want, But I didn't...

Upvotes: 2

Related Questions