How to use includes method In Typescript
In this approach, we are using the includes method with the map function and JSON.stringify to compare objects in the array. The map function is used to create an array of string representations of each object, and then the includes method checks if the string representation of the given object obj is present in the array.
Syntax:
array.includes(searchElement[, fromIndex]);
Example: The below example uses includes method to check if an array includes an object in TypeScript.
Javascript
interface inter { name: string; topic: string; } const arr: inter[] = [ { name: 'GFG1' , topic: 'TypeScript' }, { name: 'GFG2' , topic: 'JavaScript' }, { name: 'GFG3' , topic: 'React' }, ]; const obj: inter = { name: 'GFG' , topic: 'JavaScript' }; const res: boolean = arr .map(obj => JSON .stringify(obj)) .includes(JSON.stringify(obj)); console.log(res); |
Output:
true
How to Check if an Array Includes an Object in TypeScript ?
In TypeScript, checking if an array includes an object consists of comparing the object’s properties within the array elements. We can compare and check this using three different approaches some method, find method, and includes method.
There are several ways to check if an array includes an object in TypeScript which are as follows:
Table of Content
- Using some method
- Using find method
- Using includes method