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

早过忘川 提交于 2020-12-14 12:33:05

问题


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
}

回答1:


Use 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]));



回答2:


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



来源:https://stackoverflow.com/questions/62565632/best-method-to-extract-selected-columns-from-2d-array-in-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!