Devoid Design Devoid Design - 2 months ago 13
Javascript Question

Finding the sum of subarrays

I'm working on a very large array of subarrays full of numbers that I want to reduce into one sum for each subarray.

Example:



var arr = [[1,2,3], [4,5,6]];

arr.forEach(function(item) {
item.reduce(function(a, b) {
return a + b;
});
});
console.log(arr);

//I want arr to equal [[6], [15]];





My solution just returns the original array element

Answer

Try something like this:

var arr = [[1,2,3], [4,5,6]];
var newArr = [];

arr.forEach(function(item) {
  item = item.reduce(function(a, b) {
    return a + b;
  });
  newArr.push([item]);
});
console.log(newArr);

To be a bit more concise, you can use the values passed to the forEach callback: the item you're currently iterating through, the index of that item, and the array itself:

arr.forEach(function(item, index, array) {
  array[index] = [array[index].reduce(function (a, b) {
    return a + b;
  })];
});