Pages

Tuesday, 2 June 2020

Sort through data using JavaScript Filter

The following Google Apps Script is designed to sort through a large amount of data and return only that which matches a certain criteria, using the JavaScript Filter method. In this example there is a list of students belonging to various groups (A1, B1, C1, etc) and we want to compile a list of those that belong to a Group ID that we specify.
Screenshot of dataset sorted by Group ID
Screenshot of dataset sorted by Group ID

Once we get all of the data from the spreadsheet we can pass it to the filterData function as a name:value pair array. From here we need to use the 'filter' method to create a new array (from the existing array) with the elements (or rows of data in this example) that fall under a given criteria.

Our criteria is that we want the Group ID (column D of the Data sheet) to match the Group ID we specify on the Results sheet and only return those rows of data. So within the 'filter' method we create a function that performs an if statement to look for a match - which if that row of data does match then it becomes part of the new array:
var filteredData = data.filter(function (id) {
   
    if (id[3] == filterId) {
      return id;
    }

   
});

Sort through data using JavaScript Filter download

No comments:

Post a comment