October 3, 2022

Remove Duplicates From An Array in Javascript

Remove Duplicates From An Array in Javascript

Its is easy to remove duplicates from a Javascript array by converting the array to a Set, then back into an array. This works because a Set is an object that can contain only 1 of each item.

let arrayWithDuplicates = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8 ]

let setWithoutDuplicates = new Set(arrayWithDuplicates)
let arrayWithoutDuplicates = Array.from(setWithoutDuplicates)

Using the spread operator (...) we can do this in 2 lines

let arrayWithDuplicates = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8 ]

let arrayWithoutDuplicates = Array.from([...new Set(arrayWithDuplicates)])