0

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.

1
  • 1
    I'm not sure whether this is the direct answer for is this the best way to do it?. So I answer as a comment. As another direction, how about the following sample scripts? 1. const v = config.reduce((o,[c],i) => (o[String.fromCharCode(97 + i)] = c, o), {}) In this script, the values can be retrieved by v.a, v.b,,,. 2. config.forEach(([c],i) => this[String.fromCharCode(97 + i)] = c) In this case, the values can be retrieved by a, b,,,. But in this case, these variables are declared as the global. Commented Dec 3, 2021 at 2:15

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! so clean looking!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.