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)
If you don't want to use Sets (because reasons). This might be the shortest:
Does this method keep it's ordering, all the time?
No,
Object.keys(arr.reduce((acc, val) => { acc[val] = val return acc }, { }))
is essentiallyObject.fromEntries(arr.map((val) => [val, val]))
. So, it is essentially the same method asSet
I would argue that the classical way might be as short, while keeping order, not sure about performance, though.
Actually, the third argument of filter callback is
arr
as well, so you can.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 typesGreat 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)
Oldie but goldie 👍