admin管理员组

文章数量:1323335

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

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

Share Improve this question asked Sep 30, 2016 at 17:19 user6732041user6732041 1
  • arr.map(a => a.reduce((p,c) => p+c)) – Redu Commented Sep 30, 2016 at 17:27
Add a ment  | 

6 Answers 6

Reset to default 5

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

.reduce doesn't modify the original array. You can use .map and return the new value, like this:

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

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

Or with map and arrow functions:

var arr = [[1,2,3], [4,5,6]];
var result = arr.map(item => item.reduce((a, b) => a + b));
console.log(result); // [ 6, 15 ]

ES5 Syntax

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

arr.map(function (item) {
  return item.reduce(function (a, b) {
    return  a+b;
  });
})

ES6 Syntax

arr.map(item => {
  return item.reduce((a,b) => a+b);
})

If you want the summed result to be in their own list, I would break the problem down in to 2 steps:

const arr = [[1,2,3], [4,5,6]];
const sumList = (xs) => [xs.reduce((x, y) => x + y, 0)];

alert(arr.map(sumList)); //=> [[6], [15]]

Maybe this is what you want?

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

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

本文标签: javascriptFinding the sum of subarraysStack Overflow