In JavaScript, there are many ways to remove duplicate elements from an array. You can use the filter()
method or the Set
object to remove all repeated items from an array.
Let us say that we have the following array that contains duplicate elements:
const numbers = [1, 2, 3, 2, 4, 4, 5, 6]
Remove duplicates usingfilter()
method
The following example demonstrates how you can use the filter()
method to remove all duplicate elements from the above array and returns only unique values:
const unique = numbers.filter((value, index) => {
return numbers.indexOf(value) === index
})
// print unique array
console.log(unique) // [ 1, 2, 3, 4, 5, 6 ]
The filter()
method primarily creates a new array populated with all array elements that match a specific condition. Any array element that fails or returns false
, will be excluded from the filtered array.
This approach works in all modern browsers and Internet Explorer 9 and higher. However, you can use a polyfill to support older browsers.
Remove duplicates using Set
A Set
is a special object type introduced in ES6 that stores a collection of unique values. Since each value stored in a Set
must be unique, passing any duplicate item will be removed automatically at the initialization time.
Here is an example:
const numbers = [1, 2, 3, 2, 4, 4, 5, 6]
// remove duplicates
const unique = Array.from(new Set(numbers))
// print unique array
console.log(unique) // [ 1, 2, 3, 4, 5, 6 ]
In the above example, we have to use the Array.from()
method to convert the Set
back to an array. This step is necessary because a Set
is not an array.
Alternatively, you could also use the spread operator to perform the Set
to an array conversion:
const unique = [...new Set(numbers)]
This approach will only work in modern browsers and in a Node.js application. If you want to support old browsers, use the filter()
method.
Read this guide to learn more about JavaScript arrays and their methods.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.