Home > Software engineering >  Google Apps Script Function output can not be stored in a variable
Google Apps Script Function output can not be stored in a variable

Time:03-10

I have an array that I want to flatten in order to iterate over it. I get the array and then flatten it with the following function:

var Array = ss.getRange("G2:G").getValues(); ArrayFlat = flatten(Array);

Flatten helperfunction

function flatten(array) {
  var flattenedArray = [];

  for (var i = 0; i < keycloakAmountOfRows; i  ) {
    flattenedArray.push(array[i][0])
  }
  return flattenedArray;
}

I would expect the same output for the last two following logs, but I get different logs.

function test() {
  Logger.log(Array) // unflattened array
  Logger.log(flatten(Array)) // flattended array
  Logger.log(ArrayFlat) // []
}

Can someone point me in the right direction, i.e. where the error lies?

CodePudding user response:

Try:

ss.getRange("G2:G").getValues().flat();

Array.flat()

function flatten() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const array = ss.getDataRange().getValues();
  var fA = [];
  if(array.length) {
    array.forEach((r,i) => {
      if(array[i].length) {
        r.forEach((c,j) => {
          fA.push(c);
        })
      }
    })
  } else {
    fA.push(r[0])
  }
  Logger.log(JSON.stringify(fA));
}
  • Related