Filtering Data in Apps Script
This post is a corrected post after AI explains the code included in the book “Google Apps Script 101: Building Work Automation For Free”. Added a strikethrough when editing what AI has written, and added color when edited by author
Table of Contents
Summary
This blog post will demonstrate how to filter data in Apps Script using the filter
method. We will write a function that retrieves data from a Google Spreadsheet and filters it based on a specified criteria.
Code
1 2 3 4 5 6 7 8 |
function filterCat() { const SS = SpreadsheetApp.getActiveSpreadsheet() const T_SHEET6 = SS.getSheetByName('시트6') const data = T_SHEET6.getDataRange().getValues() let dataFilter = data.filter(row => row[0] == '고양이') Logger.log(dataFilter) } |
Code Explanation
The code defines a function named filterCat
. It retrieves the active Google Spreadsheet and gets a specific sheet named ‘시트6’. The getDataRange()
method is used to get the range of data in the sheet, and the getValues()
method retrieves the values from the range.
The filter
method is then applied to the data array, using an arrow function as the filtering condition. In this example, the code filters the data based on the first column matching the value ‘cat’. The filtered data is stored in the dataFilter
variable.
Finally, the filtered data is logged using the Logger.log()
function.
Example
Suppose we have a Google Spreadsheet with a sheet named ‘시트6’ that contains a column of animal names in the first column. We want to filter the data to only include rows where the animal type is ‘cat’.
Column A | Column B | Column C |
---|---|---|
Type | Name | Age |
cat | Pong | 10 |
Puppy | Tami | 12 |
cat | ping | 10 |
When the filterCat()
function is executed, the filtered data is logged to the Apps Script logger.
cat | Pong | 10 |
cat | ping | 10 |
AI Prompt
Write a function that filters data from a Google Spreadsheet based on a specified condition. Retrieve the active spreadsheet, get a specific sheet by name, and use the filter
method to filter the data. Log the filtered data.