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

GoogleScript – map an array of array from elements of another array

I’m working on a GAS that takes a dataRange from Sheet (columns + rows) only to return a selection of columns. The selection of columns is done from elements in an array.

let dtARange = [["Number", "Created", "X", "V", "E", "Name", "Section", "School", "Organisation", "Teacher1","Teacher2","Hour1","Hour2"],
["3","September","x","x","","ThisClass","ThisSection","MySchool","MyOrganisation","Mr John","Mr Paul","Noon","Evening"],
["4","May","","x","","ThisOtherClass","ThisOtherSection","MyOtherSchool","MyOtherOrganisation","Mr Favreau","Mr Vinx","Noon","Evening"]]; 

let [headers,...data] = dtARange;

//I have headers and data. Now I have a selection that comes in an array

let mySelection = ["Number","Name","School","Teacher1"]; // for example

What I need to be able to do is to retrieve what’s in data from these headers in mySelection. I don’t need the headers really, but to build a new array that has the data from all the columns I pick.

I’m trying several different things but it doesn’t really work out so far (in my real sheet, I have hundreds of rows of course).

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

Thank you if you can help,

>Solution :

In your situation, how about the following sample script?

Sample script:

let dtARange = [["Number", "Created", "X", "V", "E", "Name", "Section", "School", "Organisation", "Teacher1", "Teacher2", "Hour1", "Hour2"],
["3", "September", "x", "x", "", "ThisClass", "ThisSection", "MySchool", "MyOrganisation", "Mr John", "Mr Paul", "Noon", "Evening"],
["4", "May", "", "x", "", "ThisOtherClass", "ThisOtherSection", "MyOtherSchool", "MyOtherOrganisation", "Mr Favreau", "Mr Vinx", "Noon", "Evening"]];
let [headers, ...data] = dtARange;
let mySelection = ["Number", "Name", "School", "Teacher1"]; // for example

// I added below script.
const indexes = mySelection.map(e => headers.indexOf(e));
const res = data.map(r => indexes.map(c => r[c]));
console.log(res)

Reference:

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