Home > Back-end >  How do I add the values from three arrays?
How do I add the values from three arrays?

Time:05-08

Is there an easy way to add the elements of arrays together? Let's say I have 3 arrays.

[15,22,35,40]
[10,20,12,20]
[11,24,14,22]

What I want to do is add up the totals so it would be:

[36,66,61,82]

and then overwrite [11,24,14,22] with those values.

Forgot to add the code I already have:

function combineItems(){
  sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var dataRange = sheet.getDataRange();
  var values = dataRange.getValues();
  for (var i = 0; i < values.length; i  ) {
    var row = "";
    for (var j = 0; j < values[i].length; j  ) {
      if (values[i][j] == "Product A") {
        medData = sheet.getRange(i   1, 7, 1, 4).getValues();
        console.log(medData);
      }
      if (values[i][j] == "Product B") {
        smData = sheet.getRange(i   1, 7, 1, 4).getValues();
        console.log(smData);
      }
      if (values[i][j] == "Product C") {
        newData = sheet.getRange(i   1, 7, 1, 4).getValues();
        console.log(newData);
      }
    }
  }
}

So I want to add up Product A, Product B, and Product C and then overwrite Product C with those new totals.

CodePudding user response:

Solution:

function myFunction(data) {

  return data[data.length-1].map((i, index) => i = 
           data.reduce((prev, curr) => prev   curr[index], 0)
         )

}

Example:

const productA = [15,22,35,40]
const productB = [10,20,12,20]
const productC = [11,24,14,22] 

const newData = myFunction([productA, productB, productC])

/** 

Expected Output:

  [36.0, 66.0, 61.0, 82.0]

**/

How It Works:

Taking the input of a multidimensional array, we alter the last row in place (.map()) by reducing (.reduce()) all values of the input data by index for each row. (Reduce each column of the data into the last row.)

Suggested Reading:

  • Related