1

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?

31piy
  • 23,323
  • 6
  • 47
  • 67

4 Answers4

3

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);
31piy
  • 23,323
  • 6
  • 47
  • 67
1

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)
brk
  • 48,835
  • 10
  • 56
  • 78
1

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);
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
0

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);
Atul Sharma
  • 9,397
  • 10
  • 38
  • 65