Home > Software engineering >  Google App Scripts / Javascript: Return columns from array maintaining the desired order
Google App Scripts / Javascript: Return columns from array maintaining the desired order

Time:05-26

I'm trying to write a function that will return a specific array of rows/columns but I want it to only contain a specific set of columns and I want it to follow a specific order.

I have managed to achieve it to take only the columns I want however it seems that it's not keeping the order and instead it's ordering it ascending.

Current block of code:

function filterRows(){
  let mainSheet = spreadSheet.getSheetByName('Main');
  var sourceData = SpreadsheetApp.getActive().getRangeByName("full_list").getValues();
  var outputData = getCols(sourceData ,[1,2,3,4,10,7,8,11,9,12]);

  var startRow = 12;
  mainSheet.insertRowsAfter(startRow, outputData.length); 
 
  mainSheet.getRange(startRow,1,outputData.length,outputData[0].length).setValues(outputData);
}

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

Basically the output data array is not keeping the intended order of columns provided in the getCols function call which would be: [1,2,3,4,10,7,8,11,9,12]

What changes would you suggest me to make to the getCols function in order to achieve the intended result?

CodePudding user response:

If you're just trying to get the specific columns from the rows in your array,

Try:

const targetColumns = [1,2,3,4,10,7,8,11,9,12] 
const outputData = sourceData.map(row => targetColumns.map(col => row[col-1]))

Function:

function getCols(arr, cols) {

  return arr.map(row => cols.map(col => row[col-1]))

}

Test:

const sourceData = [
    [`A1`, `B1`, `C1`, `D1`, `E1`],
    [`A2`, `B2`, `C2`, `D2`, `E2`]
  ]

const targetColumns = [1,3,4]
const outputData = sourceData.map(row => targetColumns.map(col => row[col-1]))

/* OUTPUT (outputData)

 [
   [A1, C1, D1], 
   [A2, C2, D2]
 ]

*/

If this isn't what you're looking for please let me know!

CodePudding user response:

Try this

function filterRows(){
  let mainSheet = spreadSheet.getSheetByName('Main');
  var outputData = SpreadsheetApp.getActive().getRangeByName("full_list").getValues().map(([a,b,c,d,e,f,g,h,i,j,k,l]) => [a,b,c,d,j,g,h,k,l]);;
  var startRow = 12;
  mainSheet.insertRowsAfter(startRow, outputData.length); 
  mainSheet.getRange(startRow,1,outputData.length,outputData[0].length).setValues(outputData);
}
  • Related