在应用程序脚本中从2D数组提取选定列的最佳方法 [英] Best method to extract selected columns from 2d array in apps script
问题描述
我正在使用Google Apps脚本.如果我从范围A1:E5之类的范围开始,那就是一个5x5的数组.我想返回范围C1:D5,一个5x2数组.从二维数组开始,仅返回选定的列".基本上就是这样.我认为这是一项基本操作,但我确实很挣扎.我在下面有我的代码,但是我可以使用任何使用数组的选项(而不是范围,以便避免不必要地对服务器执行ping操作).请注意,我确实希望能够为列传递数组参数,所以[2,3,4]或[2]或[3,4]不仅是单个值或静态值.感谢您的帮助.
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
}
推荐答案
使用 Array#filter 与地图:
/**
* 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]));
这篇关于在应用程序脚本中从2D数组提取选定列的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!