user13746257
user13746257

Reputation:

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).

Thank you if you can help,

Upvotes: 2

Views: 46

Answers (1)

Tanaike
Tanaike

Reputation: 201673

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:

Upvotes: 1

Related Questions