Home > Software engineering >  Filtering google sheets import data before import
Filtering google sheets import data before import

Time:09-29

I have a script that imports data from a google sheet. Before importing the data into the new sheet I would like to filter it. In Column2 are our Cost centers listed and all cost centers starting with '41' should be filtered and imported to the sheet. Right now I'm a little bit blocked in saying filtering by column2 where the string startswith '41'.

  // Gets the active sheet.
  var sheet = SpreadsheetApp.getActiveSheet();
  
  // Gets a different spreadsheet from Drive using
  // the spreadsheet's ID. 
  var employeeActuals = SpreadsheetApp.openById(
    "1yL_0eB9b6CQLOshjPglDA-MnP2HZdLeIrKh4DO-qN0c" 
  );

  // Gets the sheet, data range, and values of the
  // spreadsheet stored in employeeActuals.
  var employeeActualsSheet = employeeActuals.getSheetByName("Overview")
  var range = employeeActualsSheet.getDataRange();
  var rangeValues = range.getValues();

  var databasis = rangeValues.filter(function(Item){return Item[1] === String().startsWith(["41"]) })

  Logger.log(databasis); ```

CodePudding user response:

Try something like this:

function myfunk() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const ss = SpreadsheetApp.openById(gobj.globals.testsourceid);
  const esh = ss.getSheetByName("Sheet1")
  const range = esh.getDataRange();
  const vs = range.getValues();
  let data = vs.filter(e => e[0].startsWith('17'))

  Logger.log(data);
}

Data:

COL1 COL2 COL3
10,1 10,2 10,3
11,1 11,2 11,3
12,1 12,2 12,3
13,1 13,2 13,3
14,1 14,2 14,3
15,1 15,2 15,3
16,1 16,2 16,3
17,1 17,2 17,3
18,1 18,2 18,3
19,1 19,2 19,3
20,1 20,2 20,3

output:

12:09:45 PM Notice  Execution started
12:09:45 PM Info    [[17,1, 17,2, 17,3]]
12:09:47 PM Notice  Execution completed

CodePudding user response:

The getValues() method returns a two dimensional string so in order to filter out the values, you will also need a loop in order to the filtering properly:

var filterVals = [];
for (let i = 0; i < rangeValues.length; i  ) {
    var values = rangeValues[i].filter(element => element.toString().startsWith('41'));
    filterVals.push(values);
}
let databasis = filterVals.filter(element => element.toString() != "")
Logger.log(databasis);

Reference

  • Related