Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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]
];
functiongroup(data) {
    let group = newMap;
    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)
        elsefor (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...

Post a Comment for "In Javascript Is There A Way To Sum Elements In Multi-dimensional Arrays, Grouped On Other Elements In The Array"