Removing duplicate values from an array is something that we’ve to do sometimes in our JavaScript apps.
In this article, we’ll look at how to get all unique values from a JavaScript array.
The filter Method
We can use an array instance’s filter
method to filter out any duplicate values that are found.
For instance, we can write:
const onlyUnique = (value, index, arr) => {
return arr.indexOf(value) === index;
}
const a = ['a', 1, 'a', 2, '1'];
const unique = a.filter(onlyUnique);
We have the onlyUnique
function that we use as the callback for the filter
method.
The callback for the filter
method accepts the value that we’re iterating through as the first parameter.
The 2nd parameter is the index of the element we’re iterating through.
arr
is the array we’re iterating through.
So we can call indexOf
or arr
to get the index of the first instance of value
.
If it isn’t the same as index
, then we know it’s a duplicate value.
We can pass the function into the filter
method to get the unique value.
Therefore, unique
is [“a”, 1, 2, “1”]
Converting to a Set and Back to an Array
Another way that we can remove duplicates from an array is to convert an array into a set and then convert the set back to an array.
We can convert a set to an array with the spread operator since a set is an iterable object.
For instance, we can write:
const a = ['a', 1, 'a', 2, '1'];
const unique = [...new Set(a)];
console.log(unique)
We create a set with the Set
constructor.
This will create a set, which doesn’t allow duplicate values inside it.
So all the duplicate values will be removed.
Then we use the spread operator to convert the set back to an array.
unique
should be the same value as before.
Lodash
Lodash has the uniq
method that returns an array with the duplicate values removed.
For instance, we can write:
const a = ['a', 1, 'a', 2, '1'];
const unique = _.uniq(a)
console.log(unique)
to remove all the duplicate items from a
.
Conclusion
We can remove duplicate items from an array with sets and the spread operator.
Also, we can do the same thing with the filter
and indexOf
methods.
And we can also use Lodash to remove duplicate items from an array.