Home > Mobile >  How to map specific column using GAS?
How to map specific column using GAS?

Time:02-11

From @soMario's answer to a certain question, getting the data of specific column can be done like this:

The following will get columns b,d,f,g from the range A:G.

const rawData = ss.getRange("A:G").getValues().map(([,b,,d,,f,g]) => [b,d,f,g]);

How can I get the same, but using getRange(2,1,sheet.getLastRow(),7) instead?

Thank you!

CodePudding user response:

when you getValues() of any range, it is stored as one array of many arrays, which looks like this, structurally for the range A1:G3 :

[ [ , , , , , , ], [ , , , , , , ], [ , , , , , , ] ]

when you want a specific "column", say column 4 of that range, in javascript/appscript it means you want the 4th element of each of the arrays in the array. When counting from 0, the 4th element is the 3rd "index".

When using the mapping function, each of the elements of the array being mapped is assigned any variable you want. It is common to use "e". So for your specific case you would want to do this

const rawData = ss.getRange("A:G").map(e=>[ e[1], e[3], e[5], e[6] ]);

1,3,5 and 6 being the "indices" of columns B,D,F and G when starting to count with A as 0.

However, it's likely that you'll want a filter on your data as well to only return rows where there are values in column A. If that guess is correct, you can apply a filter before your map like this:

const rawData = ss.getRange("A:G").filter(e=>e[0]).map(e=>[ e[1], e[3], e[5], e[6] ]);
  • Related