问题
I have an array that consists of multiple arrays:
var array = [[1], [2, 1, 1], [3, 4]];
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?
回答1:
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);
回答2:
You need to loop over each of the individual array and then sum it's element and return a new array.
For returning new array you can use map
& for calculating the sum use reduce
var array = [
[1],
[2, 1, 1],
[3, 4]
];
let m = array.map(function(item) {
return item.reduce(function(acc, curr) {
acc += curr;
return acc;
}, 0)
})
console.log(m)
回答3:
You need to loop first array to find the inner arrays, and then loop all inner arrays one by one to get the sum and keep pushing it to new array after loop is complete for inner array's.
var array = [[1], [2, 1, 1], [3, 4]];
var sumArray = [];
array.forEach(function(e){
var sum = 0;
e.forEach(function(e1){
sum += e1;
});
sumArray.push(sum);
});
console.log(sumArray);
回答4:
I'd write it like:
var array = [[1], [2, 1, 1], [3, 4]];
var m = array.reduce(
(acc, curr) => acc.concat(curr.reduce((memo, number) => memo + number, 0)),
[]
);
console.log(m);
来源:https://stackoverflow.com/questions/51860880/sum-arrays-in-array-javascript