loading...
Cover image for Remove Duplicates The Shortest Way

Remove Duplicates The Shortest Way

islam profile image Islam Sayed ・1 min read
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.

Discussion

markdown guide
 

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))
}
 

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

 

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) }
 

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

 

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.

 

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)