2

I have an array of obj where there are some numb and I want to find the sum. I know how to achieve this with a simple array but in this case it seems confusing.

I tried to use reduce as we do normally in an array but it didn't work.

    const arr = [{ some: 1 }, { some: 2 }, { some: 3 }]

    const sumArr = arr.reduce((a, b) => a.some + b.some, 0)

    console.log(sumArr)

for example I know that I can do:

    const arr = [1, 2, 3, 4, 5]

    const sumArr = arr.reduce((a, b) => a + b, 0)

    console.log(sumArr)

If I have an array like [{a: 1}, {a: 2}, {a: 3}, {b: 4}, {b: 5}] I would like to find the sum for all the a and do the same for all the b.

Koyan
  • 46
  • 1
  • 7
PanosCool
  • 155
  • 2
  • 16
  • Possible duplicate of [How to sum the values of a JavaScript object?](https://stackoverflow.com/questions/16449295/how-to-sum-the-values-of-a-javascript-object) – digijay Aug 17 '19 at 08:52
  • 1
    Thank you, I didn't find this one earlier. – PanosCool Aug 17 '19 at 08:55

3 Answers3

3

Your a is the accumulator. It starts out as 0, and it sounds like you want it to turn out to be a number on every iteration, so that in the end, the whole reduce resolves to a number.

Use (a, b) => a + b.some instead:

const arr = [{ some: 1 }, { some: 2 }, { some: 3 }]

const sumArr = arr.reduce((a, b) => a + b.some, 0)

console.log(sumArr)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

a ( accumulator ) don't have some property, it's an primitive value not an object so you just need to access as a, whereas b represents the current element in loop which is an object, so you need to access value using key

const arr = [{ some: 1 }, { some: 2 }, { some: 3 }]
const sumArr = arr.reduce((a, b) => a + b.some, 0)

console.log(sumArr)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

The other answers explained the reducer problem in your method. Now for the second part of your question: you can reduce to an Object containing the sums of the different keys in the objects within an array. In other words, change the accumulator to an object and change the reducer-lambda. Something like (here's a jsfiddle to play with the code):

const raw = [{a: 1}, {a: 2}, {a: 3}, {b: 4}, {b: 5}];

const calcSums = someArray => someArray
  .reduce( (sums, val) => {
    Object.keys(val)
      .forEach( v => 
          sums[`sum-${v}`] = !sums[`sum-${v}`] ? val[v] : sums[`sum-${v}`] + val[v] );
    return sums;
  }, {} );


console.log(calcSums(raw));

// the method is generic, so this works too (as long as the values are numbers)
const raw2 = [{a: 1, b:3, c:7}, {a: 2}, {a: 3}, {b: 4}, {b: 5}, {c: 9}];
console.log(calcSums(raw2));
KooiInc
  • 119,216
  • 31
  • 141
  • 177