0

I want a report with a few selected columns from a sheet.

The selection will be as per the user input like "1,4,7,12" for including column 1,4,7 and 12 in the report.

Or the input can be "2,3" to include column 2 and 3 in the report.

//user input is saved in variable input "1,4,7,8" or "2,4" or "3,2,5"
//
var jobvals = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getDataRange().getValues();
var flds=input.split(",");
var tstr="";
for (i=1;i<jobvals.length;i++){
  for (s=0;s<flds.length;s++){
    //tstr+=jobvals[i][flds[s]]+","; //I can make a comma separated string for each row. But, I want an array for further processing
    //getting stuck here - how to make an array
  }
  tstr+="\n";
}

I want to make a new array with the selected columns. The number of columns in the result array will vary. And, the column selection will also vary.

Appreciate some ideas how to achieve this.

arul selvan
  • 616
  • 4
  • 17

2 Answers2

0

I got help from

Best method to extract selected columns from 2d array in apps script

Google Script GetRange with Filter based on values in a column AND select only certain columns

Solution

function extract_some_columns{
var jobvals = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getDataRange().getValues();

var new_array = getCols(jobvals,'['+input+']');

//new_array has only column 1,3,5 (as specified in the variable input = "1,3,5")

}



function getCols(arr,cols) {
  return arr.map(row =>
    row.filter((_,i) => cols.includes(++i)))
}


arul selvan
  • 616
  • 4
  • 17
-1

You can declare an empty array and add each element one by one by using push() function on an array. Your code should look like this:

var jobvals = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getDataRange().getValues();
var flds=input.split(",");
var tstr=[];
for (i=1;i<jobvals.length;i++){
  for (s=0;s<flds.length;s++){
    tstr.push(jobvals[i][flds[s]]); 
  }
}
Jason E.
  • 1,201
  • 1
  • 3
  • 10
  • It pushes a number of rows in new array (for each input row). I want it to push in a single row in multiple columns for each row of input data. Each row of input data must become a new row in the new array (with only some selected columns) – arul selvan Jun 05 '21 at 04:46
  • Noted on this. Apologies for the incorrect/not working code. Glad to know that you've found the solution to your concern. I hope to be of help to you in some other time. Happy coding!! – Jason E. Jun 07 '21 at 15:30