How to Filter an Array in TypeScript

  1. Syntax of the Filter Function in TypeScript
  2. Use the Filter Function to Filter Elements in TypeScript
  3. Use the Filter Function to Search for Elements in an Array in TypeScript
How to Filter an Array in TypeScript

TypeScript has an in-built function filter() to filter out elements from an array, creating a new array or a subset of the given array.

It takes in a predicate or callback function, which is made to run through every array element. Those elements which pass the test are returned in the new array by the filter() method.

Syntax of the Filter Function in TypeScript

The syntax of the filter function varies according to the use of arrow functions or the function keyword. However, the general syntax remains the same.

filter(callbackFn, thisObj);

The parameters are callbackFn, a predicate function used to test the elements against a certain condition if they are present in the resultant array. thisObj is the value to use as this when executing callbackFn.

The array has the filter prototype to return the resultant array.

var result = array.filter((element) => {...});
var result = array.filter((element, index) => {...});
var result = array.filter((element, index, arr) => {...});

var result = array.filter(function(element){...});
var result = array.filter(function(element, index){...});
var result = array.filter(function(element, index, arr){...});

The callbackFn takes in three parameters, element, index, and arr, in which index and arr are optional.

The element denotes the current element being passed to the callbackFn, and the index is the current index of the element in the array.

At the same time, the arr field is the array itself in case of any inline modifications if required.

Use the Filter Function to Filter Elements in TypeScript

The filter function can filter out certain elements in the array.

var numbers : number[] = [ 23, 44, 56, 2,  78, 21, 90, 3];

var result = numbers.filter( (num) => num % 2 == 0 );
console.log(result);

Output:

[44, 56, 2, 78, 90] 

Use the Filter Function to Search for Elements in an Array in TypeScript

The filter function can also search for elements in the array. With the help of a search query, a predicate can be formed.

var strings : string[] = [ "The hen", "A box", "The sun", "The beach"];
var searchQuery = "The"
var startingWithThe = strings.filter( str => str.indexOf(searchQuery) === 0);
console.log(startingWithThe);

Output:

["The hen", "The sun", "The beach"]

Thus the statements starting with The have been filtered out.

Shuvayan Ghosh Dastidar avatar Shuvayan Ghosh Dastidar avatar

Shuvayan is a professional software developer with an avid interest in all kinds of technology and programming languages. He loves all kinds of problem solving and writing about his experiences.

LinkedIn Website

Related Article - TypeScript Array