EN
JavaScript - how to get unique objects
0
points
In this article, we would like to show you how in JavaScript find unique objects in the array.
Below example presents how to create a function that returns unique objects using:
locks
object to store unique object as JSON,valueGetter
that creates normalized JSON objects located in the array.
Note:
As normalized JSON we understand JSON with ordered properties - below example, we take care of properties order.
Practical example:
// ONLINE-RUNNER:browser;
const getUniqueItems = (items, valueGetter) => {
const locks = {};
const result = [];
for (const item of items) {
const value = valueGetter(item);
if (value in locks) {
continue;
}
locks[value] = true;
result.push(item);
}
return result;
};
// Usage example:
const items = [
{name: 'john', age: 20},
{name: 'anna', age: 25},
{age: 20, name: 'john'},
];
const valueGetter = (item) => JSON.stringify({name: item.name, age: item.age});
const uniqueItems = getUniqueItems(items, valueGetter);
console.log(JSON.stringify(uniqueItems, null, 4));
Note:
We must remember to create the
valueGetter
function ourselves or provide a generic function.