filter() Function

In Google Apps Script, the filter() method is an array method that creates a new array with all elements that pass a specified test. It takes a callback function as an argument, which is called for each element in the array. The callback function should return a boolean value: true if the element passes the test and should be included in the new array, and false if it does not pass the test and should be excluded.

Here is an example of using the filter() method to create a new array with only even numbers:

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Create a new array with only even numbers
var evenNumbers = numbers.filter(function(num) {
  return num % 2 === 0;
});

// Output the new array
Logger.log(evenNumbers); // Outputs: [2, 4, 6, 8, 10]

In this example, we call the filter() method on the numbers array and pass a callback function that tests whether each number is even. Since the callback function returns true for even numbers and false for odd numbers, the filter() method creates a new array that contains only even numbers. The new array is assigned to a variable called evenNumbers, which is outputted to the log using the Logger.log() method.

You can also use the filter() method to create a new array with objects that meet a certain criteria:

var persons = [
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Bob", age: 40 },
  { name: "Mary", age: 35 }
];

// Create a new array with persons over 30 years old
var over30 = persons.filter(function(person) {
  return person.age > 30;
});

// Output the new array
Logger.log(over30); // Outputs: [{ name: "Bob", age: 40 }, { name: "Mary", age: 35 }]

In this example, we call the filter() method on the persons array and pass a callback function that tests whether each person’s age is over 30. Since the callback function returns true for persons over 30 and false for persons 30 or younger, the filter() method creates a new array that contains only persons over 30. The new array is assigned to a variable called over 30, which is outputted to the log using the Logger.log() method.