DEV Community

Discussion on: JavaScript - remove duplicates from array

Collapse
 
barelyhuman profile image
Reaper

I like this one and I think it's a bit faster. Uses Sets as well.
and is obviously a lot more useful in real life since you'll be using objects and keys more than just numbers.

online snippet

The snippet considers item to be have a key named id which is to be considered while making the uniqueArray
sourceArray is basically the original array with duplicates.

sourceArray.reduce((acc,item)=>{
    if(!acc.has(item.id)){
        uniqueArray.push(item);
        acc.add(item.id);
    }

    return acc;
},new Set());

Enter fullscreen mode Exit fullscreen mode

and can be written in one line if you'd like it that way.

sourceArray.reduce((acc,item)=>(!acc.has(item.id)?(uniqueArray.push(item) && acc.add(item.id) && acc):acc),new Set());
Enter fullscreen mode Exit fullscreen mode