Languages such as PHP have methods for de-duplicating arrays, but Javascript strangely does not. In PHP, you can write. array_unique
And this function will remove duplicates.
There are so many solutions online you will find for this problem. They mostly centre around using filter
and index checks, others recommend libraries like Lodash.
Forget installing libraries or writing convoluted functional programming inspired solutions. You can do this:
const arr = [1, 2, 3, 9, 1, 6, 4, 3, 9, 2, 4, 6]; const unique = [...new Set(arr)];
If you were to console log the contents of unique
using the spread operator, we convert it back to a unique array. You would get an array containing: [1, 2, 3, 9, 6, 4]
— the Set object is creating for storing unique collections, not only arrays but other types of data too.