Search for the sum of subarrays

I am working on a very large array of subarrays filled with numbers, which I want to reduce to a single 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]];
Run codeHide result

My solution just returns the original element of the array

+4
source share
6 answers

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 little more concise, you can use the values ​​passed to the forEach callback: the element you are currently viewing, the index of that element, and the array itself:

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

.reducedoes not change the original array. You can use .mapand return a new value, for example:

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);
Run codeHide result
+2
source

:

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

ES5

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

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

enter image description here

ES6

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

enter image description here

0

, , ?

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);
Hide result
0
source

If you want the final result to be on their own list, I would break the problem into two 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]]
Run codeHide result
0
source

Source: https://habr.com/ru/post/1656400/


All Articles