2

I am trying to create an array that I can filter by in Google Apps Script. This works when the array is made of values I take from the columns using range.getValues(), but doesn't work when I create a similar multidimensional array using a loop.

I am trying to create the array myself as opposed to getting it from the sheet as the columns that I want are not consecutive: one is the 10th column, the next is the 1st, the next is the 3rd etc.

This works and returns the full multidimensional range filtered properly:

function RunReport(){
  var errorSS = SpreadsheetApp.getActive();
  var enterpriseSheet = errorSS.getSheetByName('Enterprise');
  var destSheet = errorSS.getSheetByName('TestSheet');
  var sheetData = [];

  sheetData = enterpriseSheet.getRange(1, 1, 2000, 4).getValues();
  var filtered = sheetData.filter(function(dataRow){
    return dataRow[0] === 'Error';
  });
  Logger.log(filtered);
}

This 'works' but only returns the first 'column' of the array filtered by the 'Error value' but doesn't return the other parts of the array:

function RunReport(){
  var errorSS = SpreadsheetApp.getActive();
  var enterpriseSheet = errorSS.getSheetByName('Enterprise');
  var destSheet = errorSS.getSheetByName('TestSheet');

  var sheetData = [];

  var col1 = enterpriseSheet.getRange(1, 1, enterpriseSheet.getLastRow()).getValues();
  var col2 = enterpriseSheet.getRange(1, 10, enterpriseSheet.getLastRow()).getValues();
  var col3 = enterpriseSheet.getRange(1, 2, enterpriseSheet.getLastRow()).getValues();
  var col4 = enterpriseSheet.getRange(1, 3, enterpriseSheet.getLastRow()).getValues();

  for (i = 0; i < col1.length; i++)
  {
    sheetData.push(col1[i],col2[i],col3[i],col4[i]) ;
  }
  var filtered = sheetData.filter(function(dataRow){
    return dataRow[0] === 'Error';
  });
  Logger.log(filtered);
}

any ideas on what I am doing wrong?

tehhowch
  • 9,645
  • 4
  • 24
  • 42
Meruva
  • 59
  • 10
  • Possible duplicate of [How to filter an array of arrays](https://stackoverflow.com/questions/40849369/how-to-filter-an-array-of-arrays) – Rubén Feb 18 '19 at 18:18

1 Answers1

1

Issue:

  • You're getting a 2D array.
  • You're pushing a four 1D arrays.

Solution:

  • You need to push 4 elements as a single array.

Modified Script:

  • push a single array with four elements

    //sheetData.push(col1[i],col2[i],col3[i],col4[i]) ; 
    sheetData.push([col1[i][0],col2[i][0],col3[i][0],col4[i][0]]);
    
  • Alternatively, You can splice everything in col1:

    //for(i=0 ; i<col1.length ; i++)
    //{ sheetData.push(col1[i],col2[i],col3[i],col4[i]) ;}
    col1.map(function(e,i){
        e.splice(1,0,col2[i][0],col3[i][0],col4[i][0]);
        return e;
    });
    Logger.log(col1);
    

References:

TheMaster
  • 45,448
  • 6
  • 62
  • 85