How to use Set and Array.from() method In Typescript
This approach utilizes a Set to keep track of unique values based on the selected property. The Array.from() method is used to convert the created Set into a array.
Syntax:
const uniqueArray = Array.from(new Set
(originalArray.map((obj) => obj.propertyToCheck)));
Example: The below code explains the use of the Set and the Array.from() method to remove duplicate objects.
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' },
];
// Adding values of id key of each object to set
const mySet = new Set(persons.map((person) => person.id));
// Converting Set to a array using Array.from() method
const uniqueIds = Array.from(mySet);
console.log(uniqueIds);
Output:
[1, 2, 3]
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.