Skip to content Skip to sidebar Skip to footer

Sum All Properties Of Objects In Array

I have following dataset: const input = [ { x: 1, y: 3 }, { y: 2, f: 7 }, { x: 2, z: 4 } ]; I need to sum all the array elements to get following result: const output = { f:

Solution 1:

I guess this is the shortest possible solution:

const input = [
  { x: 1, y: 3 },
  { y: 2, f: 7 },
  { x: 2, z: 4 }
];

let result = _.mergeWith({}, ...input, _.add);

console.log(result);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

Docs:

If you're fine with the first element of input being replaced, you can omit the first argument:

 _.mergeWith(...input, _.add)

Solution 2:

Use Array#forEach method with Object.keys method.

const input = [{
  x: 1,
  y: 3
}, {
  y: 2,
  f: 7
}, {
  x: 2,
  z: 4
}];

// object for resultvar res = {};

// iterate over the input array
input.forEach(function(obj) {
  // get key from object and iterateObject.keys(obj).forEach(function(k) {
    // define or increment object property value
    res[k] = (res[k] || 0) + obj[k];
  })
})

console.log(res);

With ES6 arrow function

const input = [{
  x: 1,
  y: 3
}, {
  y: 2,
  f: 7
}, {
  x: 2,
  z: 4
}];

var res = {};

input.forEach(obj =>Object.keys(obj).forEach(k => res[k] = (res[k] || 0) + obj[k]))

console.log(res);

Solution 3:

You could iterate the keys and sum.

var input = [{ x: 1, y: 3 }, { y: 2, f: 7 }, { x: 2, z: 4 }],
    sum = input.reduce((r, a) => (Object.keys(a).forEach(k => r[k] = (r[k] || 0) + a[k]), r), {});
console.log(sum);

Solution 4:

use _.mergeWith

_.reduce(input, function(result, item) {
    return _.mergeWith(result, item, function(resVal, itemVal) {
        return itemVal + (resVal || 0);
    });
}, {});

Solution 5:

const input = [
  { x: 1, y: 3 },
  { y: 2, f: 7 },
  { x: 2, z: 4 }
];

functionsumProperties(input) {
  return input.reduce((acc, obj) => {
    Object.keys(obj).forEach((key) => {
      if (!acc[key]) {
        acc[key] = 0
      }
      acc[key] += obj[key]
    })
    return acc
  }, {})
}

console.log(
  sumProperties(input) 
)

Post a Comment for "Sum All Properties Of Objects In Array"