Home > Blockchain >  Multiple Variable Assignment in Javascript/GAS - Is this the most compact way to do it?
Multiple Variable Assignment in Javascript/GAS - Is this the most compact way to do it?

Time:12-04

Ok so I have a spreadsheet which we extract a 2d array of values from. But really I want one variable per line of this 2d array. The following code does work... but is this the best way to do it?

function testAssignments(){
  config = ss.getRange("C2:C6").getValues();//2D Array
  result = []
  config.forEach(x => result.push(x[0]))
  var [a,b,c,d,e] = result;
  console.log(a,b,c,d,e);
}

I also tried the line config.forEach(x=> x=x[0]) but that didn't work for some reason.

CodePudding user response:

Use .flat instead of .forEach and .push. If you want a different variable name for each element, there isn't a better way.

const [a,b,c,d,e] = ss.getRange("C2:C6").getValues().flat();//1D Array
//or
const [[a],[b],[c],[d],[e]] = ss.getRange("C2:C6").getValues();
  • Related