Typescript filter array [With 15 real examples]

In this Typescript tutorial, we will see what is a filter method in typescript, and how to filter an array in typescript. Also, we will see different examples of how we can filter array in typescript:

  • Typescript filter array
  • Typescript filter array of objects
  • Typescript filter array of objects by key
  • Typescript filter array of objects contains
  • Typescript filter array from another array
  • Typescript filter array multiple values
  • Typescript filter array and get first
  • Typescript filter array async
  • Typescript array filter arrow functions
  • Typescript filter array by index
  • Typescript filter array by date
  • Typescript filter array by enum
  • Typescript filter array by type
  • Typescript filter array by id
  • Typescript filter array duplicates
  • Typescript array filter delete

Learn more about Typescript array.

Typescript filter array

The filter() method in typescript returns a new array containing all items that pass the test specified by the supplied function.

Syntax:

array.filter(callback,[, thisObject])

As this method accepts two parameters, i.e. callback and thisObject.

  • callback: as this is a function, test each item in an array
  • thisObject: This is the Object that will be used as this when the callback is executed.

Let’s see an example how we can filter the item from an array.

For example, we will see how we can filter the number that is negative from an array. Open the code editor, create a file named as app.ts file, then write the below code:

function isNegetive(element:any, index:any, array:any)
	{
	return element < 0;
	}
		
	// Driver code
	var arr = [ 11, 89, -23, 7, 98,-18 ];
	
	// check for positive number
	var value = arr.filter(isNegetive);
	console.log( value );

To compile the code, run the below command and you can see the output in the console.

ts-node app.ts
Typescript filter array
Typescript filter array

This is how we can use a typescript filter array.

Read How to check type of variable in Typescript

Typescript filter array of objects

Here we will see an example of how to filter an array of objects in typescript.

To filter an array of objects in typescript:

  • On the array, use the filter function
  • Check to see whether the current object’s property fits the requirement
  • The array returned will only contain items that meet the requirement.

So let’s see an example of how we can filter an object from array of objects.

For example, there is an array of policies, so we need to filter objects containing ‘IT’. In the app.ts file write the below code:

const itPolicy = [
		{ name: 'Information security policy', department: 'accounting' },
		{ name: 'Leave Policy', department: 'human resources' },
		{ name: 'Service Management Policy', department: 'IT' },
		{name: ' Policy', department: 'IT'}
	  ];
	  
	  const result = itPolicy.filter((obj) => {
		return obj.department === 'IT';
	  });
	  
	  // 👇️ [
  //{ name: 'Service Management Policy', department: 'IT' },
  //{ name: ' Policy', department: 'IT' }
//]
	  console.log(result);

To compile the code and run the below command and you can see the output in the console.

ts-node app.ts
typescript filter array of objects by property value
Typescript filter array of objects

This is an example of a Typescript filter array of objects.

Read Typescript type annotation

Typescript filter array of objects by key

Here we will see how we can filter an array of objects by key in typescript.

Object. keys() generates an array whose components are strings holding the names (keys) of an object’s properties.

For example, we will filter the objects from an array based on the selected key. In the app.ts file write the below code:

const employee:any = {
    Alex: { username: 'alex112', age:19 },
    John: { key: 'johnl1', age:21 },
    Ron: { key: 'ron01', age:24 },
   Rock : { key: 'rock009', age:28 }
};

const selectedEmployee = ['Alex', 'Ron'];

const filteredEmployee = Object.keys(employee)
    .filter(key => selectedEmployee.includes(key))
    .reduce((obj:any, key:any) => {
        obj[key] = employee[key];
        return obj;
  }, {});

console.log(filteredEmployee);

To compile the code run the below command and you can see the below output in the console.

ts-node app.ts
Typescript filter array of objects by key
Typescript filter array of objects by key

This is an example of a typescript filter array of objects by key

Typescript filter array of objects contains

Here we will see how to filter an array of objects, it contains the value in typescript.

For example, we have an array of names, so if the array contains the name Alex, then it will return an array in a console, else it will return an empty array.

In the app.ts file write the below code:

const arr = [{name: 'Alex'}, {name: 'Ron'}, {name: 'John'}];
console.log(arr.filter(e => e.name === 'Alex')); // [ { name: 'Alex' } ]

To compile the code run the below command and you can see the result in the console:

ts-node app.ts
Typescript filter array of objects contains
Typescript filter array of objects contains

This is an example of a typescript filter array of objects contains.

Typescript filter array from another array

Here we will see an example of how to filter an array from another array in typescript.

For example, we will filter the grp1 array from the grp2 array by using the filter method in typescript.

In the app.ts file write the below code to filter an array from another array:

const grp1 = [
	{
	  id: 1,
	  uName:"Ron"
	  
	},
	{
	  id: 2,
	  uName:"Alex"
	},
	{
		id: 3,
		uName:"John"
	},
	{
		id: 4,
		uName:"Ron"
	},
	{
	  id: 5,
	  uName:"Christen"
	}
  ];
  
  const grp2 = [
	{
		id: 1,
		uName:"Ron"
		
	  },
	  {
		id: 5,
		uName:"Christen"
	  }

To compile the code and run the below command and you can see the output in the console:

Typescript filter array from another array
Typescript filter array from another array

This is an example of Typescript filter array from another array

Read Typescript Identifiers and Keywords

Typescript filter array multiple values

Here we will see how to filter an array for multiple values using typescript.

For example, we will filter the multiple values from an array in typescript. In the app.ts file write the below code:

var num = [11, 13, 14, 22, 61, 17, 50, 19, 21, 18];
var result = num.filter(num => num < 40 && num >=12);
console.log(result);

To run the code we will run the below command and you can see the output in the console:

ts-node app.ts
Typescript filter array multiple values
Typescript filter array multiple values

This is an example of typescript filter array multiple values

Typescript filter array and get first

Here we will see how to filter the array to get the first element in the typescript.

For example, we will see how we can get the first element from an array using the filter method. In the app.ts file write the below code:

let arrayOfString = ["Typescript", "Java", "Python","Javascript"];

var firstValue = arrayOfString.filter(e => typeof e!==undefined).shift();

console.log("First element of array is: " + firstValue );

To compile the code, run the below command and you can see the output in the console:

ts-node app.ts
Typescript filter array and get first
Typescript filter array and get first

This is an example of typescript filter array and gets first.

Typescript array filter arrow functions

Here we will see an example of how to filter using arrow functions in typescript.

For example, we will use the filter method with arrow functions in typescript, to get the even number from an array. In the app.ts file write the below code:

let numbers = [-23,-20,-17, -12, -5, 0, 1, 5, 12, 19, 20];

let even_array = numbers.filter(function(value) {
    return value%2 === 0; });

console.log(even_array);

To compile the code, run the below command and you can see the result in the console:

ts-node app.ts
Typescript array filter arrow functions
Typescript array filter arrow functions

This is an example of Typescript array filter arrow functions.

Read Typescript hello world program for beginners

Typescript filter array by index

Here we will see how to filter an array by index in typescript.

For example, we will create a function that will calculate the odd number from an array, then by index, we will get the first odd number from an array in typescript. In the app.ts file write the below code:

function isodd(element: number, index: number, array: any) {

	return (element % 2 == 1);

}
// Driver code

var arr = [13, 88, 22, 7, 98];

// check for odd number

var value = arr.filter(isodd)[1];

console.log(value);

To compile the code, run the below command and you can see the result in the console:

ts-node app.ts
Typescript filter array by index
Typescript filter array by index

This is an example of a Typescript filter array by index.

Typescript filter array async

Here we will see how we can filter an array with async in typescript.

This time, the async variant is a little more involved, and it operates in two stages. The first asynchronously passes the array through the boolean function, generating true/false values. The second step is a synchronous filter that leverages the previous step’s results.

Let’s see an example of how we can filter an array with async in typescript. In the app.ts file write the below code:

async function result() {
	const arr = [12, 20, 31];
	const asyncRes = await Promise.all(arr.map(async (j) => {
	   return j + 2;
	}));
	console.log(asyncRes);
	}
	result();

To compile the code, run the below command and you can see the output in the console.

ts-node app.ts
Typescript filter array async
Typescript filter array async

This is an example of a Typescript filter array async.

Typescript filter array by date

Here we will see how we can filter array by date using typescript.

For example, we have an array of dates, from this we will get the dates between two dates. In the app.ts file write the below code:

const dates= ['11/12/2022','13/11/2022','14/11/2022','15/11/2022'];
let filteredDate = dates.filter(dateFilter);
function dateFilter(date:string){
	return date >= '13/11/2022' && date <= '15/11/2022';

}
console.log(filteredDate);

To compile the code, run the below command and you can see the result in the console:

ts-node app.ts
Typescript filter array date
Typescript filter array date

This is an example of Typescript filter array date.

Read TypeScript Enum

Typescript filter array by enum

Here we will see how to filter enum values from an array in typescript.

Enums, also known as enumerated types in TypeScript, are data structures of a fixed length that store a collection of constant values. Each of these constant values is referred to as an enum member. Enums are helpful for specifying characteristics or values that have a limited number of potential values.

Let’s see an example of how we can filter all enum values from an array in typescript.

To receive all enum values as an array, send the enum to the Object. values() function, e.g. const values = Object.values(StringEnum) (StringEnum). Because enums in TypeScript are real objects that exist at runtime, the Object. values function will return an array of the enum’s values.

In the app.ts file write the below code, to filter the enum values from an array

enum CountryEnum {
	India = 'IN',
	UnitedKingdom = 'UK',
	Australia = 'AUS',
  }
  
  const values1 = Object.values(CountryEnum);
  // 👇️ [ 'IN', 'UK', 'AUS' ]
  console.log(values1);
  
  const keys1 = Object.keys(CountryEnum);
  // 👇️ [ 'India', 'UnitedKingdom', 'Australia' ]
  console.log(keys1);
  
  // ✅ For NUMERIC Enums
  enum NumericEnum {
	India,
	UnitedKingdom,
	Australia,
  }
  
  const values2 = Object.keys(NumericEnum).filter((v) => !isNaN(Number(v)));
  console.log(values2); // 👉️ ['0', '1', '2']

To compile the code, run the below command and you can see the output in the console:

ts-node app.ts
Typescript filter array by enum
Typescript filter array by enum

This is an example of a Typescript filter array by an enum.

Typescript filter array by id

Here we will see an example of how we can filter an array by id in typescript.

For example, we have an array of id and user name, so here we will filter an array having id =4. In the app.ts file, write the below code:

const grp = [
		{
		  id: 1,
		  uName:"Ron"
	
		},
		{
		  id: 2,
		  uName:"Alex"
		},
		{
			id: 3,
			uName:"John"
		},
		{
			id: 4,
			uName:"Ammy"
		},
		{
			id: 4,
			uName:"Henry"
		},
		{
		  id: 5,
		  uName:"Christen"
		}
	  ];
	  let result= grp.filter(x => x.id === 4).map(x=>x.uName);
	  console.log(result);

To compile the below code, run the below command, and you can see the output in the console.

ts-node app.ts
Typescript filter array by id
Typescript filter array by id

This is an example of a Typescript filter array by id.

Read TypeScript Set and Weakset

Typescript filter array duplicates

Here we will see an example to filter the duplicates from an array in typescript.

For example, we will filter the duplicates from an array using the filter method in typescript. In the app.ts file write the below code:

 const array= [12,25,12,25,56,90,30,30]
 let result = array.filter((item,index)=>array.indexOf(item)!== index);
 console.log("duplicate items" + result)

To compile the code, run the below command, you can see the output in the console.

ts-node app.ts
Typescript filter array duplicates
Typescript filter array duplicates

This is an example of Typescript filter array duplicates

Typescript array filter delete

Here we will see an example of how we can filter the array and delete items from an array in typescript.

For example, we will filter an array to delete items based on the condition. In the app.ts file, write the below code :

var num = [11, 20, 35, 40, 55, 67, 75, 8, 19, 0];
    var filtered = num.filter(function(value, index, arr){ 
        return value > 35;
    });

	console.log(filtered);

To compile the code, run the below command and you can see the result in the console.

ts-node app.ts
Typescript array filter delete
Typescript array filter delete

This is an example of a Typescript array filter delete.

Conclusion

In this Typescript tutorial, we learned all about the typescript filter method, with different examples. Here are the examples we have done are listed below:

  • Typescript filter array
  • Typescript filter array of objects
  • Typescript filter array of objects by key
  • Typescript filter array of objects contains
  • Typescript filter array from another array
  • Typescript filter array multiple values
  • Typescript filter array and get first
  • Typescript filter array async
  • Typescript array filter arrow functions
  • Typescript filter array by index
  • Typescript filter array by date
  • Typescript filter array by enum
  • Typescript filter array by type
  • Typescript filter array by id
  • Typescript filter array duplicates
  • Typescript array filter delete

You may like the following typescript tutorials:

>