JavaEar 专注于收集分享传播有价值的技术资料

# how to sum arrays of array?

### 问题描述

#### 英文原文

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?

#### 中文翻译

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?

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?

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?

### 2个回答

最佳答案

1. #### 英文原文

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)

#### 中文翻译

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)

2. 参考答案2

3. #### 英文原文

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

#### 中文翻译

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