Sum arrays in array (JavaScript)(在数组中求和数组(JavaScript))
问题描述
我有一个由多个数组组成的数组:
I have an array that consists of multiple arrays:
var array = [[1], [2, 1, 1], [3, 4]];
现在我想得到一个数组,它的元素是变量array"中每个数组的总和.在这个例子中,这将是 var sum = [1, 4, 7].我该怎么做?
Now I want to get an array that has elements that are the sums of each array in the variable "array". In this example that would be var sum = [1, 4, 7]. How can I do this?
推荐答案
您可以使用 Array#map
返回新项目.可以使用 Array#reduce
准备项目以汇总所有内部元素.
You can use Array#map
to return the new items. The items can be prepared using Array#reduce
to sum up all the inner elements.
var array = [[1], [2, 1, 1], [3, 4]];
var newArray = array
.map(arr => arr.reduce((sum, item) => sum += item, 0));
console.log(newArray);
这篇关于在数组中求和数组(JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!