Airscript Learn to use Airtable scripts

Using 'filter'

The Javascript filter method is great for iterating through your records and finding those that meet a certain criteria. In this post we’ll retrieve a set of records from Airtable, enter a search term and return the records that contain this term. Here’s our data set - a simple list of email addresses:

Here’s our script:


let table = base.getTable('People');
let query = await table.selectRecordsAsync();

let searchTerm = await input.textAsync('Enter your search term');

let filteredRecords = query.records.filter(person => {
    return person.getCellValue('Email').includes(searchTerm)
})

console.log(filteredRecords);

Let’s walk through this step by step.

The first two lines:


let table = base.getTable('People');
let query = await table.selectRecordsAsync();

are the common table and query definitions.

We then use the Airtable input.textAsync method to get input from the user. Their input is assigned to the variable searchTerm for use in the filter further on in the script.

Now we come to the main part of the script.


let filteredRecords = query.records.filter(person => {
    return person.getCellValue('Email').includes(searchTerm)
})


When you apply the filter method on an array, the result is another array of records which meet the filter criteria. We define the variable filteredRecords to be our new result array. As we iterate through our original results array, each record is assigned to the variable person.

The code inside the curly brackets:


return person.getCellValue('Email').includes(searchTerm)

returns the current person record to the new array if the value of Email for the person includes the searchTerm.

Finally, we console.log our new array to see the results. Run the script and you should see something like this:

In practice, you would probably have other code that runs after the filter action - post the data to another table or an external app for example.