Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Efficient way to get unique objects from array of objects, by object property?

Here is my array of objects

const array = [ 
  {id: 1, data: "foo"}, 
  {id: 1, data: "bar"}, 
  {id: 2, data: "baz"} 
]

I want to remove all duplicate objects by its id and return only the array of objects that have an unique id.

Expected result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[ 
  {id: 2, data: "baz"} 
]

This is what I have now: O(n^2)

function getUnique(array) {
    const newArray = []

    for (let obj of array) {
        if (array.filter(x => x.id === obj.id).length === 1) {
            newArray.push(obj)
        }
    }

    return newArray
}

Whats the more efficient way to achieve this?

Is it possible to get the time-complexity to O(n) or O(n log n)?

>Solution :

const array = [{
        id: 1,
        data: "foo"
    },
    {
        id: 1,
        data: "bar"
    },
    {
        id: 2,
        data: "baz"
    }
]

let map = {};

array.forEach(x => {
    map[x.id] = (map[x.id] || 0) + 1
});

console.log(array.filter(x => map[x.id] === 1))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading