Languages
[Edit]
EN

JavaScript - get unique objects from array

3 points
Created by:
Fletcher-Peralta
778

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.

 

See also

  1. TypeScript - get unique objects from array

  2. JavaScript - convert object to JSON with ordered properties

Alternative titles

  1. JavaScript - how to get unique objects from array?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join