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

I'm working in google apps script. If I start with a range like range A1:E5, that's a 5x5 array. I want to return range C1:D5, a 5x2 array. Start with a 2d array and return only selected 'columns'. That's basically it. I think it's a fundamental operation, but I'm really struggling. I have my code below, but I'm open to any options that use arrays (not ranges, so as to avoid pinging the server unnecessarily). Note that I do want to be able to pass an array parameter for columns, so [2,3,4] or [2] or [3,4], not just a single or static value. Thanks for any help.

/**
 * extracts selected 'columns' (2nd dimension) from 2d array
 *
 * @arr {array} larger 2d array to be subset
 * @cols {array} subset of columns, eg, [3,4]
 * @return 2d array with only selected cols
 * @customfunction
 */
function getCols(arr,cols) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();  

  var arrRows = [];
  var arrCols = [];
  
  for(var r=0;r<arr.length;r++){
    arrCols = [];// reset snippet
  for(var c=0;c<cols.length;c++){
    arrCols.push([arr[r][cols[c]]]); // iterate to make 1xc array snippet
  }
    arrRows[r].push(arrCols); // iterate to add each row
  }
  
  return arrRows; // return new arr subset that only has requested cols
}


Solution 1:[1]

function myfunc() {
  const ss=SpreadsheetApp.getActive();
  var vs=ss.getActiveSheet().getDataRange().getValues().map(function(r){return [r[2],r[3]];});
  ss.getActiveSheet().getRange(ss.getActiveSheet().getLastRow()+1,1,vs.length,vs[0].length).setValues(vs);
}

This will output columns C and D right below the current data

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cooper