Skip to content Skip to sidebar Skip to footer

Sum Arrays In Array (javascript)

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 variabl

Solution 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);

Solution 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)

Solution 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);

Solution 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);

Post a Comment for "Sum Arrays In Array (javascript)"