Jeremy
Jeremy

Reputation: 59

JavaScript reduce inner array of array and create answer array

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.

Upvotes: 0

Views: 333

Answers (4)

Akrion
Akrion

Reputation: 18515

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)

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

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

Upvotes: 2

Mohammad Usman
Mohammad Usman

Reputation: 39322

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

Upvotes: 2

iagowp
iagowp

Reputation: 2494

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

list.map(array => array.reduce((a, b) => a + b))

Upvotes: 2

Related Questions