There are multiple ways you can remove duplicates from a JS array. My favorite one is by using a Set
and a spread
operator.
So, I start with an array that has duplicates and construct a set from it using new Set(arr)
.
The Set
by definition holds only unique elements, so I can be sure that there won’t be any duplicates.
And finally, I spread out the newly created set into an array and save it as uniqueOnly
.
const arr = [1, 1, 2, 3, 3, 3, 4];
const uniqueOnly = [...new Set(arr)];
console.log(uniqueOnly); // [ 1, 2, 3, 4 ]
Enjoy!