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?

0

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

what is the approach to get the result like this [6,5,1] which is adding each value of array to the other array in the same index.
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)

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.