Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Google Apps Script Function output can not be stored in a variable

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading