How to use an Object to Track Unique Objects In Typescript
This approach involves using an object to keep track of unique objects based on a specific property. It iterates through the array of objects, and for each object, it checks whether the property value already exists in the object. If it does not exist, it adds the object to the result array and adds the property value to the tracking object. This approach ensures that only unique objects are included in the result.
Syntax:
function removeDuplicates(arr: any[], key: string): any[] {
return arr.reduce((unique, item) => {
if (!unique.find(obj => obj[key] === item[key])) {
unique.push(item);
}
return unique;
}, []);
}
Example: The following code demonstrates the use of the removeDuplicates function to remove duplicate objects based on the id property from an array of objects.
function removeDuplicates(arr: any[], key: string): any[] {
return arr.reduce((unique, item) => {
if (!unique.find((obj : any) => obj[key] === item[key])) {
unique.push(item);
}
return unique;
}, []);
}
interface Person {
id: number;
name: string;
}
const arrayOfObjects: Person[] = [
{ id: 1, name: "nikunj" },
{ id: 2, name: "dhruv" },
{ id: 1, name: "nikunj" },
{ id: 3, name: "yash" },
{ id: 2, name: "dhruv" },
];
const uniqueArray = removeDuplicates(arrayOfObjects, "id");
console.log(uniqueArray);
Output:
[{
"id": 1,
"name": "nikunj"
}, {
"id": 2,
"name": "dhruv"
}, {
"id": 3,
"name": "yash"
}]
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.