Parth Patel
Parth Patel

Reputation: 63

How to add values of similar keys in an array of object

I have an array of objects that looks like this:

[
 {1: 22},
 {1: 56},
 {2: 345},
 {3: 23},
 {2: 12}
]

I need to make it look like this:

[{1: 78}, {2: 357}, {3: 23}]

Is there a way I could make it so that it can sum up all the values that have the same key? I have tried using a for each loop but that hasn't helped at all. I would really appreciate some help. Thank you!

Upvotes: 1

Views: 1013

Answers (2)

Mark
Mark

Reputation: 92440

You can use reduce for this to build up a new object. You start with an empty object and set the key to the value from the original array or add it to an existing object already. Then to get an array, just map it back.

let arr = [{1: 22},{1: 56},{2: 345},{3: 23},{2: 12}];

let tot = arr.reduce((a,obj) => {
    let [k, v] = Object.entries(obj)[0]
    a[k] = (a[k] || 0) + v
    return a
}, {})

let final = Object.entries(tot).map(([k,v]) => {
    return {[k]:v}
})
console.log(final);

Upvotes: 1

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

You can use reduce to make an object of the sum, then convert that object to an array of objects:

function group(arr) {
    var sumObj = arr.reduce(function(acc, obj) {
        var key = Object.keys(obj)[0];                  // get the key of the current object (assuming there is only one)
        if(acc.hasOwnProperty(key)) {                   // if there is an entry of that object in acc
            acc[key] += obj[key];                       // add to it the current object's value
        } else {
            acc[key] = obj[key];                        // otherwise, create a new entry that initially contains the current object's value
        }
        return acc;
    }, {});

    return Object.keys(sumObj).map(function(key) {      // now map each key in sumObj into an individual object and return the resulting objects as an array
        return { [key]: sumObj[key] };
    });
}

Example:

function group(arr) {
    var sumObj = arr.reduce(function(acc, obj) {
        var key = Object.keys(obj)[0];                  // get the key of the current object (assuming there is only one)
        if(acc.hasOwnProperty(key)) {                   // if there is an entry of that object in acc
            acc[key] += obj[key];                       // add to it the current object's value
        } else {
            acc[key] = obj[key];                        // otherwise, create a new entry that initially contains the current object's value
        }
        return acc;
    }, {});

    return Object.keys(sumObj).map(function(key) {      // now map each key in sumObj into an individual object and return the resulting objects as an array
        return { [key]: sumObj[key] };
    });
}

var arr = [ {1: 22}, {1: 56}, {2: 345}, {3: 23}, {2: 12} ];
console.log(group(arr));

Upvotes: 0

Related Questions