Reputation: 59
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
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
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
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
Reputation: 2494
You need to iterate both the outer and the inner arrays.
list.map(array => array.reduce((a, b) => a + b))
Upvotes: 2