0

Array of arrays:

list = [[1, 2, 3], [4, 5, 6]];

I want to reduce (combine) each inner array (1+2+3) and (4+5+6) and then put those results 6 and 15 in their own array like [6, 15].

I have below code:

list.reduce((a, b) => a + b);

but it's just strangely combining everything in all the arrays.

Mohammad Usman
39.6k20 gold badges99 silver badges101 bronze badges
asked Dec 8, 2018 at 18:28

4 Answers 4

2

You need to iterate both the outer and the inner arrays.

list.map(array => array.reduce((a, b) => a + b))
answered Dec 8, 2018 at 18:30
Sign up to request clarification or add additional context in comments.

Comments

2

Use .map() with .reduce():

let list = [[1, 2, 3], [4, 5, 6]];
let reducer = (a, b) => (a + b);
let result = list.map(arr => arr.reduce(reducer));
console.log(result);

answered Dec 8, 2018 at 18:31

Comments

2

You can do it like this

map() with map we iterate on every element of arr.

reduce() - with reduce we reduce each element to a single value.

let arr = [[1,2,3],[4,5,6]];
let op = arr.map(e => e.reduce( (a, b) => a + b, 0) );
console.log(op);

answered Dec 8, 2018 at 18:30

Comments

1

You can also achieve this with Array.from since its second parameter is Array.map function and inside you can do your Array.reduce for the summation:

const data = [[1, 2, 3], [4, 5, 6]]
const result = Array.from(data, x => x.reduce((r,c) => r+c))
console.log(result)

answered Dec 8, 2018 at 18:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.