How to use filter() and findIndex() methods In Typescript
This approach involves using the filter() function along with the findIndex() method to create a new array containing only the unique objects.
Syntax:
const uniqueArray = originalArray.
filter((obj, index, self) =>index ===
self.findIndex((o) => o.propertyToCheck === obj.propertyToCheck)
);
Example: The below code uses filter() and the findIndex() method to remove duplicate objects from an array.
interface Person {
id: number;
name: string;
}
const persons: Person[] = [
{ id: 1, name: 'Ram' },
{ id: 2, name: 'Shyam' },
{ id: 1, name: 'Ram' },
{ id: 3, name: 'Sita' },
];
const uniquePersons = persons.
filter((person, index, self) => index ===
self.findIndex((p) => p.id === person.id)
);
console.log(uniquePersons);
Output:
[
{ "id": 1, "name": "Ram" },
{ "id": 2, "name": "Shyam" },
{ "id": 3, "name": "Sita" }
]
How to Remove Duplicates from an Array of Objects using TypeScript ?
We are given an array of objects and we have to check if there are duplicate objects present in the array and remove the duplicate occurrences from it. Otherwise, return the array as it is.