Yash Jain
Yash Jain

Reputation: 822

Add values of n number of arrays

I have an array of arrays containing values, it looks something like this

var values = [[23,45,12,67],[26,35,65,23],[45,73,12,54],[32,45,65,86]];

I want to add all the arrays present inside values variable such like

sum = [126,198,154,230]

126 = 23+26+45+32

198 = 45+35+73+45

I tried this using Array.prototype.map() but maybe I am not getting the perfect logic to do that so needed help here. How to add the values of n arrays.

Upvotes: 1

Views: 88

Answers (5)

Yosvel Quintero
Yosvel Quintero

Reputation: 19080

You can use Array.prototype.map() combined with Array.prototype.reduce()

Code example:

const values = [[23, 45, 12, 67], [26, 35, 65, 23], [45, 73, 12, 54], [32, 45, 65, 86]];
const result = values.map((v, index, array) => v.reduce((a, c, i) => a + array[i][index], 0));
    
console.log(result);

Upvotes: 0

Abhishek Pandey
Abhishek Pandey

Reputation: 346

Your code some what like this,

var sum;
var values = [[23,45,12,67],[26,35,65,23],[45,73,12,54],[32,45,65,86]];
values.forEach(myFunction);

function myFunction(item, index) {
     item..forEach(ArraySum)
}

function ArraySum(item, index) {
     sum=sum+item;
}

Upvotes: 0

Kasabucki Alexandr
Kasabucki Alexandr

Reputation: 630

My solution is:

const values = [[23,45,12,67],[26,35,65,23],[45,73,12,54],[32,45,65,86]];

const res = values.reduce((curr, next) => {

  let length = curr.length;
  for(let i = 0; i < length; i++) {
    curr[i] += next[i]
  }
  return curr;
});

console.log(res);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386728

Right, you could map the sum of single values, but you need to reduce the arrays as well.

var values = [[23, 45, 12, 67], [26, 35, 65, 23], [45, 73, 12, 54], [32, 45, 65, 86]],
    result = values.reduce((a, b) => a.map((v, i) => v + b[i]));
    
console.log(result);

Upvotes: 4

Hassan Imam
Hassan Imam

Reputation: 22574

You can use array#reduce with array#forEach. Iterate over your array, for each array inside the array, sum its value in a new array and add the other arrays to result based on the index.

var values = [[23,45,12,67],[26,35,65,23],[45,73,12,54],[32,45,65,86]],
    result = values.reduce((r,a) => {
      a.forEach((v,i) => r[i] = (r[i] || 0) + v);
      return r;
    }); 
console.log(result);

Upvotes: 0

Related Questions