The Array method filter() in Apps Script

The Array method filter() is used to filter an array based on a set of conditions. This method returns a new array with the filtered values.

Syntax

array.filter(callbackFunction)

Parameters

callbackFunction (required):

  • This is the function that will be executed once for every element in the array. This function is where you need to specify the conditions that need to be checked. If all the conditions are met, the corresponding value will be included in the filtered array.

The callbackFunction can accept three arguments:

  • value (required): The current value being processed.

  • index (optional): The index of the value in the array.

  • array (optional): The original array that the filter() method was called on.

Return value

The filter() method returns a new array containing values from the original array that meet the conditions set forth in the callbackFunction.

How does the filter() Array method work?

The filter() method will execute the callbackFunction once for every element in the array. If the callbackFunction returns true (or a value that is treated as true by Apps Script), the element will be included in the filtered array that is returned by the filter() method. If the callbackFunction returns false, the corresponding value will not be included in the filtered array.

Examples

Example 1: Using the filter() Array method to filter out values that are not a number

Example 1.1

In the code below, the function isNumber(value) is the callbackFunction parameter in the filter() method. This function is executed once for every element in the array values and it returns true if the element is a number and false otherwise.The array filteredValues is returned by the filter() method and it only contains numeric values from the original array.

function filterEx1_1() {
  var values = [1, -10, "apple", 25, "orange"];
  var filteredValues = values.filter(isNumber);
  Logger.log(filteredValues);
}

function isNumber(value) {
  return typeof value === "number";
}

Output

[1.0, -10.0, 25.0]

Example 1.2

Instead of defining the function isNumber() separately and then passing it as a parameter, you can also define it in-line. The code below shows you how to do this.

function filterEx1_2() {
 var values = [1, -10, "apple", 25, "orange"];
 var filteredValues = values.filter(function(value) {
   return typeof value === "number";
 });
 Logger.log(filteredValues);
}

Output

[1.0, -10.0, 25.0]

Conclusion

In this tutorial, you learned how to use the filter() Array method to create a new array that only contains those elements from the original array that meet a set of conditions.


Have feedback for me?

I'd appreciate any feedback you can give me regarding this post.

Was it useful? Are there any errors or was something confusing? Would you like me to write a post about a related topic? Any other feedback is also welcome. Thank you so much!