使用可变过滤器过滤二维阵列

时间:2019-04-12 20:52:54

标签: javascript arrays multidimensional-array google-apps-script google-sheets

我正在尝试将一个数组分解为几个不同的数组,以将信息粘贴到几张纸上。我在使用单独的数组(sheetCheck)动态过滤主数据数组(bigArray)时遇到麻烦。如果我输入一个静态过滤器,即“ 02A”,则过滤器可以工作。如何修改过滤器以接受变量信息?

function testArray (){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  //Get full array of Budget Pricing Breakdown Sheet
  var originalArray = ss.getRangeByName('XxTestRange').getValues();
  //Delete unused columns from array. Only Leaves sheetNumber, description, qty, UM, unitCost
  var newArray = originalArray.map(function(row){return[row[0],row[5],row[6],row[7],row[10]];});
  //Delete unused rows that have a value of X in the sheetNumber
  var bigArray = newArray.filter(function(item){return item[0] != "X";});

  //Get array of Applicable Tabs
  var originalSheetsArray = ss.getRangeByName('XxTestRange2').getValues();
  //Remove unused column
  var newSheetsArray = originalSheetsArray.map(function(row){return[row[0],row[2]];});
  //Delete not applicable rows
  var sheetCheckBad = newSheetsArray.filter(function(item){return item[1] != "Not Applicable"});
  //Separate just appicable trades
  var sheetCheck = sheetCheckBad.map(function(row){return[row[0]];});

  for (var i=0; i<sheetCheck.length;i++){
    var sheetNumber = sheetCheck[i];
    //Logger.log(sheetNumber)
    var pasteArray = bigArray.filter(function(item, sheetNumber){return item[0] == sheetNumber})
    //var pasteArray = bigArray.filter(filterSheetLogic)
    Logger.log(sheetNumber);
    Logger.log(pasteArray);
  }
}

//Pull individual Arrays based on sheet numbers
var filterSheetLogic = function(item, sheetNumber){
  if (item[0] == sheetNumber){
    return true;
  } else {
    return false;
  }
}

1 个答案:

答案 0 :(得分:1)

你不能打电话

 bigArray.filter(function(item, sheetNumber) ...

因为过滤器的回调获得了自己的参数。在这种情况下,sheetNumber始终等于数组的索引012等。

我的案例是构建一个结构以生成有效的回调。例如

/**
 * The big array filter's builder. It's a fabric
 * @param {string} sheetNumber
 * @returns {object} The filter's callback
 */
var filterBuilder_ = function(sheetNumber) {
  return function(item, _, __) {
    return item[0] == sheetNumber;
  };
};

在此之后,将主循环更改为

for (var i = 0; i < sheetCheck.length; i++) {
  var sheetNumber = sheetCheck[i][0];
  var bigArrayfilter = filterBuilder_(sheetNumber);
  var pasteArray = bigArray.filter(bigArrayfilter);
  Logger.log(sheetNumber);
  Logger.log(pasteArray);
}

如果我对任务的理解不正确,我深表歉意。