Christian_g3k0 Christian_g3k0 - 3 months ago 21
Javascript Question

javascript: manipulate array of objects

I have an array like this:

arr = [
{name:'Tom', a:1, b:1, c:0},
{name:'Sam', a:0, b:1, c:1},
{name:'Tom', a:0, b:0, c:1},
{name:'Sam', a:1, b:2, c:1},
{name: 'Jack', a:1, b:2, c:0}
]


and I need to sum the properties of the objects with the same name and then to slice duplicates:

arr = [
{name:'Tom', a:1, b:1, c:1},
{name:'Sam', a:1, b:3, c:2},
{name: 'Jack', a:1, b:2, c:0}
]


How is it possible in pure JavaScript?

Answer

Proposal for random properties, with a hash table.

var arr = [{ name: 'Tom', a: 1, b: 1, c: 0 }, { name: 'Sam', a: 0, b: 1, c: 1 }, { name: 'Tom', a: 0, b: 0, c: 1 }, { name: 'Sam', a: 1, b: 2, c: 1 }, { name: 'Jack', a: 1, b: 2, c: 0 }],
    grouped = [];

arr.forEach(function (a) {
    if (!this[a.name]) {
        this[a.name] = { name: a.name };
        grouped.push(this[a.name]);
    }
    Object.keys(a).forEach(function (k) {
        if (k !== 'name') {
            this[k] = (this[k] || 0) + a[k];
        }
    }, this[a.name]);
}, Object.create(null));

console.log(grouped);