EN
TypeScript - get unique objects from array
3
points
In this article, we would like to show you how to find unique objects in the array using TypeScript.
The main idea to find unique objects is to create text representation for each object and check them if are unique.
Practical example:
// ONLINE-RUNNER:browser;
const getUniqueItems = <T extends unknown> (items: T[], keyGetter: (item: T) => string): T[] => {
const locks: Record<string, boolean> = {};
const result: T[] = [];
for (const item of items) {
const key = keyGetter(item);
if (key in locks) {
continue;
}
locks[key] = true;
result.push(item);
}
return result;
};
// Usage example:
interface User {
name: string;
age: number;
}
const items: User[] = [
{ name: 'john', age: 20 },
{ name: 'anna', age: 25 },
{ age: 20, name: 'john' },
];
const keyGetter = (item: User): string => item.name + ' ' + item.age;
const uniqueItems = getUniqueItems(items, keyGetter);
console.log(JSON.stringify(uniqueItems, null, 4));
Output:
[
{
"name": "john",
"age": 20
},
{
"name": "anna",
"age": 25
}
]
Note: it is important to create correct
valueGetter
function or use universal one, e.g.JSON.stringify()
improved with ordered properties.