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.

4 Answers 4

2

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

list.map(array => array.reduce((a, b) => a + b))
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);

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);

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)

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.