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.

2

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer, now I understand better how it works. :)
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));

1 Comment

Thank you! Very well explained and easy to understand.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.