如何使用另一个数组的过滤索引来过滤一个数组?

时间:2019-07-19 20:15:27

标签: javascript arrays google-apps-script filter

我当前的代码将“值”,“注释”和“背景色”的相同数据范围的值捕获到3个单独的数组中。然后,它按嵌套数组中的第一项过滤Values数组,仅返回与定义的statArray数组项匹配的项。现在,我希望通过过滤后的Value数组中返回项的索引来过滤其他两个数组过滤器(“注”,“背景”)。这样,当我设置Backgrounds和Notes数组时,它们可以正确地重叠在值上。

function moveAllNew() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var activeSheet = SpreadsheetApp.getActiveSheet();
  var activeSheetName = activeSheet.getName();
  var lastRow = activeSheet.getLastRow();
  var lastColumn = activeSheet.getLastColumn();
  var statArray = ["Captures Sent ?","QA In Progress ?","Bagging in Progress 01 ?","Bagging in Progress 02 ?","Bag Sent ?","Bag Rejected ❌","Bag Accepted ✅","Captured ?",""];
  var rowHeaderCount = 3;
  var rowStart = 4;
  var columnFormulaB = 2;
  var columnFormulaS = 19;
  var columnFormulaAC = 29;
// gets the range of the current sheet
  var activeRange = activeSheet.getRange(rowStart,1,lastColumn-rowHeaderCount,lastColumn);
  var activeRangeFormulaB = activeSheet.getRange(rowStart,columnFormulaB,lastRow-rowHeaderCount);
  var activeRangeFormulaS = activeSheet.getRange(rowStart,columnFormulaS,lastRow-rowHeaderCount);
  var activeRangeFormulaAC = activeSheet.getRange(rowStart,columnFormulaAC,lastRow-rowHeaderCount);
// creates array of the active sheet (values, notes, backgrounds, and formula columns (B, S, AC))
  var activeRangeValues = activeRange.getValues();
  var activeRangeNotes = activeRange.getNotes();
  var activeRangeBackgrounds = activeRange.getBackgrounds();
  var activeRangeFormulaB = activeRangeFormulaB.getFormulasR1C1();
  var activeRangeFormulaS = activeRangeFormulaS.getFormulasR1C1();
  var activeRangeFormulaAC = activeRangeFormulaAC.getFormulasR1C1();
// filtered QA arrays
  var qaSheet = ss.getSheetByName("QA ?");
  var qaRangeValues = activeRangeValues.filter(function(item){return item[0] === statArray[0] || item[0] === statArray[1];});
  var qaRangeNotes = activeRangeNotes.filter(function(item){return item[0] === statArray[0] || item[0] === statArray[1];});
  var qaRangeBackgrounds = activeRangeBackgrounds.filter(function(item){return item[0] === statArray[0] || item[0] === statArray[1];});
  Logger.log(qaRangeValues);
  Logger.log(qaRangeNotes);
  Logger.log(qaRangeBackgrounds);

当前qaRangeValuesqaRangeNotes数组将恢复为空,因为statArray项目既不是颜色也不是音符值。

1 个答案:

答案 0 :(得分:2)

确定lastRow时,您可能打算使用lastColumn而不是activeRange

无论如何,您需要执行一些操作来访问当前索引,并且在拥有索引的同时,还要对其他大小相等的数组进行操作。

一个例子:

var qaData = {values: [], notes: [], bgs: [] };
activeRangeValues.forEach(function (row, idx) {
  if (row[i] === statArray[0] || row[i] === statArray[1]) {
    qaData.values.push(row);
    qaData.notes.push(activeRangeNotes[idx]);
    ...
});
// Use the qaData object