DEV Community

Cover image for Remove Duplicates The Shortest Way
Islam Sayed
Islam Sayed

Posted on

Remove Duplicates The Shortest Way

function removeDuplicate(arr) {
  return [...new Set(arr)]
}

Remove duplicates from an array in javascript the shortest way.👍Using Set object where it only contains unique values (remove repeated ones). Then with spread operator spreads the values into an array again. 😎

Entfernen Sie Duplikate auf kürzestem Weg aus einem Array in #Javascript. Dann spreizt der Operator mit spread die Werte wieder in ein Array.

Top comments (7)

Collapse
 
vatsaluppal1997 profile image
vatsal-uppal-1997

If you don't want to use Sets (because reasons). This might be the shortest:

function removeDuplicates(arr) {
    return Object.keys(arr.reduce((acc, val) => {
        acc[val] = val
        return acc
    }, { })).map(val => Number(val))
}
Collapse
 
jinglescode profile image
Jingles (Hong Jing)

Does this method keep it's ordering, all the time?

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

No, Object.keys(arr.reduce((acc, val) => { acc[val] = val return acc }, { })) is essentially Object.fromEntries(arr.map((val) => [val, val])). So, it is essentially the same method as Set

I would argue that the classical way might be as short, while keeping order, not sure about performance, though.

function removeDuplicates(arr) {
    return arr.filter((a, i) => arr.indexOf(a) === i)
}

Actually, the third argument of filter callback is arr as well, so you can .filter((v,i,a)=>a.indexOf(v)==i)

Array.prototype.distinct = function () { return this.filter((v, i, a) => a.indexOf(v) == i) }
Collapse
 
briancodes profile image
Brian • Edited

Just to note that Set values are compared by reference for uniqueness - this can catch you out if your Array contains objects rather than primitive types

Collapse
 
islam profile image
Islam Sayed

Great advice! But how can we consider objects as duplicates even if they have same properties when they are passed by reference. So I think objects case is not applicable to this problem.

Collapse
 
briancodes profile image
Brian • Edited

If you considered these objects duplicates [{id:1}, {id:1}], the Set approach won't suit. In this case though you'd probably need to use a utility library like Lodash: _.uniqWith(objects, _.isEqual)

Collapse
 
sonicoder profile image
Gábor Soós

Oldie but goldie 👍