1

I know we can sum the array elements using reduce() but what if we have an array of arrays. For eg:

var result=[10,20,30];
result.reduce((a, b) => a + b)

it will return 60

but if we have

result=[
  [10,20,30],
  [20,30,40],
  [60,70,80]
]
console.log(result);

how can we get the final result as result=[60,90,210] using reduce?

1
  • It seems to me that you want to mutate the result array. In that case, do: result.forEach(function(d, i, arr) { arr[i] = d.reduce((a, b) => a + b, 0);}); Commented Sep 23, 2019 at 3:36

3 Answers 3

5

fisrt you can map and inside map use reduce

result=[
  [10,20,30],
  [20,30,40],
  [60,70,80]
  ]
const final = result.map(item => item.reduce((a, b)=> a + b, 0))

console.log(final)

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

Comments

1

You can use Array.prototype.map() to loop through each of the subarrays in the outer array. The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Once you get a subarray, follow the previous approach to find the sum using reduce().

result = result.map(subArray => subArray.reduce((a, b) => a + b))

Comments

0

If you want to use .reduce only, I suggest this code:

 result=[
  [10,20,30],
  [20,30,40],
  [60,70,80]
]
const sum = result.reduce((a, b) => {
  return [...a.concat(b.reduce((a, b) => a + b, 0))]
}, [])
console.log(sum)

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.