Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum array of arrays (matrix) vertically

How can I sum vertically all data from an array of arrays?

arrayOfArrays = [{
    label: 'First Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  },
  {
    label: 'Second Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  },
  {
    label: 'Third Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  }
];

var result = arrayOfArrays.reduce(function(array1, array2) {
  return array1.data.map(function(value, index) {
    return value + array2.data[index];
  }, 0);
});

console.log(result)

The output should be the vertical sum of arrays. [3,6,9,12,15,18,21,24]

The problem is that array1 return always as undefined.

like image 647
Irimescu Cosmin Avatar asked Aug 26 '19 10:08

Irimescu Cosmin


People also ask

Can you sum an array?

In order to find the sum of all elements in an array, we can simply iterate the array and add each element to a sum accumulating variable.

How do you sum a matrix in Javascript?

x = [[1,2,3,4], [5,6,7,8], [9,10,11,12] ]; var sum = function(arr) { return arr. reduce(function(a, b){ return a + b; }, 0); }; x. map(function(row, i) { return sum(x.

How do you sum all elements in an array in Matlab?

S = sum( A , 'all' ) computes the sum of all elements of A . This syntax is valid for MATLAB® versions R2018b and later. S = sum( A , dim ) returns the sum along dimension dim . For example, if A is a matrix, then sum(A,2) is a column vector containing the sum of each row.


1 Answers

You code is almost correct but with 1 issues.

You are looping on accumulator. This will be an array of number in second iteration. Instead loop over array2 or current item.

Idea of .reduce is to have same signature for all iteration. If you do not pass default value for accumulator, first iteration will be of type Array<{ label: string, data: Array<number>}> and second iteration will be just Array<number>. So you can skip behavior for first iteration by passing default value as []. Now the calculation will break as array[n] will be undefined. For this, you can use a default value of 0.

So your calculation will look like:

value + (array1[index] || 0)

Following is a sample:

arrayOfArrays = [{
    label: 'First Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  },
  {
    label: 'Second Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  },
  {
    label: 'Third Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  }
];

var result = arrayOfArrays.reduce(function(array1, array2) {
  return array2.data.map(function(value, index) {
    return value + (array1[index] || 0);
  }, 0);
}, []);

console.log(result)
like image 109
Rajesh Avatar answered Nov 14 '22 00:11

Rajesh