DEV Community

[Comment from a deleted post]
Collapse
 
casperns profile image
Zelimir Stefanovic

Nice example. Also, another way:

let sett = new Set();
return arr.map((v, index) => { 
   if(sett12.has(v.id)) {
       return false
   } else {
       sett12.add(v.id);
       return index;
   } 
});

Or if we want just unique values then:

function noDuplicates(arr) {
    return [...new Set(arr.map(v => v.id))];
}
Collapse
 
sait profile image
Sai gowtham

wow, good solution.

The final solution with typos fixed.

function getUnique(arr){
let set = new Set();
return arr.map((v, index) => { 
   if(set.has(v.id)) {
       return false
   } else {
       set.add(v.id);
       return index;
   } 
  }).filter(e=>e).map(e=>arr[e]);


}
Collapse
 
tcomtom profile image
Tom Shimada

This was a great article. This helped me with my project. I was using faker to create some data but faker created duplicate names in an array of objects, but the client didn't want any duplicates.

Worked perfectly Thanks!!

Still trying to understand the code though.

Especially
.filter(e=>e).map(e=>arr[e]);

Gotta dig deeper with map and filter!

Collapse
 
nikolicstjepan profile image
Nikolić Stjepan

filter(e=>e) part fails if e (index) is 0.

Should be: filter(e => e || e === 0)