EN
JavaScript - 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 JavaScript.
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 = (items, keyGetter) => {
const locks = {};
const result = [];
for (const item of items) {
const key = keyGetter(item);
if (key in locks) {
continue;
}
locks[key] = true;
result.push(item);
}
return result;
};
// Usage example:
const items = [
{name: 'john', age: 20},
{name: 'anna', age: 25},
{age: 20, name: 'john'}
];
const keyGetter = (item) => item.name + ' ' + item.age; // change it to your own criteria
const uniqueItems = getUniqueItems(items, keyGetter);
console.log(JSON.stringify(uniqueItems, null, 4));
Note: it is important to create correct
valueGetter
function or use universal one, e.g.JSON.stringify()
improved with ordered properties.