Skip to content
Advertisement

Sum of Elements in 2D array

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!

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement