DEV Community

Discussion on: Remove Duplicates The Shortest Way

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