How to get unique items in array of linked records?

Hello everyone!

I am trying to get an array of unique items which are objects of two keys

{id: "record ID", name: "name of record"}

To filter out duplicate items I use rather complicated way. I define 3 arrays:

  • one for keeping collected data possibly having duplicates and later for cleaned data
  • two others for keeping filtered ids and names

Code looks like this:

let d = [];
let u = [];
let v = [];

d = [{id:1, name:"a"},{id:3, name:"b"},{id:3, name:"b"}];

console.log(d);

u = [...new Set(d.map(d => d.id))];
v = [...new Set(d.map(d => d.name))];
d = [];
let m = 0;
while (m < u.length){ d[m] = {id:u[m],name:v[m]}; m++ }

console.log(d);

As you can see I am using a Set to filter out duplicates. Unfortunately, this works only for simpler arrays (or I do not know how to use it in my case). Is there any easier or brief way to do that? Any valuable suggestion is much appreciated.

Hi @Andrey_Kovalev - I would also reach for Set when trying to get a unique set of values, but Set only works with primitive values or object references (but not actual objects). Here’s a method that doesn’t use Set

let array = [
    {id:1, name:"a"},
    {id:3, name:"b"},
    {id:3, name:"b"},
    {id:1, name:"a"},
    {id:1, name:"a"},
];

const result = [];
const map = new Map();
for (let item of array) {
    if(!map.has(item.id)){
        map.set(item.id, true);
        result.push(item);
    }
}
console.log(result)

This uses Map to note whether or not the loop has already seen a specific id. If not, then the current object is added to the result array; if it has been seen, then we move onto the next item in the array.

2 Likes

@JonathanBowen thank you for your solution. I will definetely try it.

1 Like

@JonathanBowen your solution is twice faster than mine. Thanks again for demonstrating how to use Maps. This was new to me.

2 Likes

This topic was solved and automatically closed 3 days after the last reply. New replies are no longer allowed.