从应用程序脚本中的二维数组中提取选定列的最佳方法

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

我在 google 应用程序脚本中工作。如果我从范围 A1:E5 之类的范围开始,那就是一个 5x5 数组。 我想要 return 范围 C1:D5,一个 5x2 数组。从二维数组开始,仅选择 return 'columns'。基本上就是这样。 我认为这是一项基本操作,但我真的很挣扎。我在下面有我的代码,但我对任何使用数组的选项持开放态度(不是范围,以避免不必要地对服务器执行 ping 操作)。请注意,我确实希望能够为列传递数组参数,因此 [2,3,4] 或 [2] 或 [3,4],而不仅仅是单个值或静态值。感谢您的帮助。

/**
 * 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
}
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);
}

这将在当前数据的正下方输出列 C 和 D

使用Array#filter with map:

/**
 * extracts selected 'columns' (2nd dimension) from 2d array
 *
 * @param {Object[][]} arr larger 2d array to be subset
 * @param {Number[]} cols Indexes of subset of columns needed starting from 1 eg, [3,4]
 * @return {Object[][]} 2d array with only selected cols
 * @customfunction
 */
function getCols(arr,cols) {
  return arr.map(row =>
    row.filter((_,i) => cols.includes(++i)))
}
console.info(getCols([[1,2,3],[4,5,6]],[1,3]));
console.info(getCols([[1,2,3],[4,5,6]],[2,3]));

相关:

What does the range method getValues() return and setValues() accept?