The filter(array, callback)
takes an array and a callback function as arguments and returns a new array with all elements passing the test defined by the callback function.
- Internally, the
filter()
method iterates over each element of the original array and passes each element to the callback function. If the callback function returns true, the element is included in the returned array. - We can use a predicate (arrow function) instead of callback functions.
- The
filter()
does not modify the original array and returns a new array which is a subset of the original array. - Because the
filter()
returns a new array, we can chain the filter result with other iterative methods such assort()
andmap()
.
function isEven(n: number) {
if(n % 2 == 0)
return true;
else
return false;
}
let numArray: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let evenNumArray: number[];
//1. Using predicate
evenNumArray = numArray.filter(n => n % 2 == 0); //boolean-valued predicate
//2. Using callback function
evenNumArray = numArray.filter(isEven);
1. Array filter() using Predicate
In the callback function, we can pass a boolean-valued predicate which will be evaluated against each array item in the sequence.
evenNumArray = numArray.filter(n => n % 2 == 0);
console.log(evenNumArray); //[0, 2, 4, 6, 8]
We can pass a multi-line predicate as well if there are more than one statement to decide if the item needs to be filtered.
evenNumArray = numArray.filter((n) => {
if (n % 2 == 0) return true;
else return false;
});
console.log(evenNumArray); //[0, 2, 4, 6, 8]
2. Array filter() using Callback Function
Each invocation of the callback function used in filter()
accepts three arguments:
- The element from the original array (Required)
- The index of the element (Optional)
- Reference to the original array which is being traversed (Optional)
function funName(currentItem:any, index?:number, array?:any[]): boolean{
//...
}
Let’s rewrite the above example one more time to understand the filter()
operation more clearly.
function isEven(n:number, i?:number, arr?:number[]) {
console.log("Argument array is : " + arr)
if(n % 2 == 0) {
console.log("Selected element value is : " + n);
console.log("Selected element index is : " + i);
return true;
}
else {
return false;
}
}
let numArray: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let evenNumArray: number[] = numArray.filter(isEven);
console.log(evenNumArray);
Program output.
Argument array is : [0,1,2,3,4,5,6,7,8,9] //Printed 9 times (for each element from 0 to 8)
Selected element value is : 0
Selected element index is : 0
Selected element value is : 2
Selected element index is : 2
Selected element value is : 4
Selected element index is : 4
Selected element value is : 6
Selected element index is : 6
Selected element value is : 8
Selected element index is : 8
[0, 2, 4, 6, 8]
3. Array filter() Examples
3.1. Filter Array of Strings
In the given example, we are checking each string in the array and discarding it if it starts with “test”.
const names = ["alex", "brian", "testName", "charles", "testD"];
const validNames = names.filter(str => !str.toLowerCase().startsWith("test"));
console.log(validNames); //Prints ["alex", "brian", "charles"]
3.2. Filter Array of Objects
Suppose we have an array of Employee
objects and want to find all employees earning more than 5k USD.
const employees = [
{id: 1, name: "alex", salary: 4000},
{id: 2, name: "brian", salary: 5000},
{id: 3, name: "charles", salary: 6000},
{id: 4, name: "david", salary: 7000},
{id: 5, name: "emily", salary: 2000}
];
const selectedEmployees = employees.filter(e => e.salary > 5000);
console.log(selectedEmployees);
//Prints
[
{id: 3, name: "charles", salary: 6000},
{id: 4, name: "david", salary: 7000}
]
4. Filter Null and/or Undefined Values
The array may contain null or undefined as values in some indices. We need to be careful when processing such arrays because they may break the program in runtime.
One possible way to cleanly filter out null or undefined values if defining a custom notEmpty() and using it everywhere we want to check a value. If we use generic type T then we can reuse this function for all kind of array types and other similar usecases.
function notEmpty<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined;
}
For example, we can filter out null and undefined values from a string array as follows:
const names = ["alex", "brian", "charles", undefined, null];
const validNames = names.filter(str => notEmpty(str));
console.log(validNames); //Prints ["alex", "brian", "charles"]
Happy Learning !!