Home > OS >  Sum of Elements in 2D array
Sum of Elements in 2D array

Time:11-08

I have a 2d array and was able to pass it from code.gs to JavaScript. The next thing I want to do is to sum all elements or numbers example in column 2.

enter image description here

I've seen this code while searching online but it add all elements in the array. I don't know how to personalize it to meet my needs.

`

var data=[
  [1,2,3],
  [4,5,6],
  [7,8,9]
  ];
  
  var sum=0;
  
  for(var i=0;i<data.length;i  ){
    for(var j=0;j<data[i].length;j  ){
      sum =data[i][j]
    }
  }
  console.log(sum);

`

In my table, I only want to get the sum of Column B, and that would be 13. then alert the value or display it in div. Thank you so much!

CodePudding user response:

To sum the second values in each array, remove the inner for loop and set the second index to 1:

var data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

var sum = 0;
for (var i = 0; i < data.length; i  ) {
  sum  = data[i][1]
}
console.log(sum);

Alternatively, use reduce():

var data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

var sum = data.reduce((acc, arr) => acc  = arr[1], 0);
console.log(sum);

CodePudding user response:

You can remove second for loop and statically set the index of B column

var data=[
  [1,2,3],
  [4,5,6],
  [7,8,9]
  ];
  
  var sum=0;
  
  for(var i=0;i<data.length;i  ){
      sum =data[i][1]
  }
  console.log(sum);

CodePudding user response:

map the data array, change it from 2D array [[1,2,3],[4,5,6],[7,8,9]] into [2,5,8],

than use reduce to add them together.

const data = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
];
const result = data.map(row => row[1]).reduce((A,B) => A   B);
console.log(result);

  • Related