Filter an array for unique values in Javascript


2 min read

Here are a few ways to filter unique values in javascript.

1. Using Set:

Set is a new data structure introduced in ES6. It is somewhat similar to an array but it does not allow us to store duplicate values.

Set Example

To filter unique values we pass an array to the Set constructor and we frame back an array from the Set object using Array.from method.

Set works perfectly with the string and number types. But it will not work with objects why? ๐Ÿค”

Take a look at this example: Set with an array of objects

Even though Tommy and Lucy are duplicated. Set was unable to identify them as duplicates.

Take a look at another example: Alt Text This is happening because when objects are compared they are compared by reference and not by value. That's why when lucy and tommy are added at first they were not added because they share the same reference. But when I added the tommy value directly it would have created a new reference.

2. Using Filter/Reduce:


We can also use Array.reduce to achieve the same kind of result.

Here the idea is findIndex or indexOf method would return the index of the first element that matches the criteria. So if the index of filter is not equal to the index returned by findIndex then the element is a duplicate.

This type will work for all types but for every element in array, we have to loop through the array again. Imagine where you want to filter in thousands of records. This approach is not an efficient one O(n^2).

3. Flag Approach:

Flag Approach

This is my favorite way to find unique especially when dealing with a large array of objects. We will loop through the array and in the flag object we will check if the value is already present. If not we will add the value to the flag object and push it to the array else we will just ignore it. In this, we will loop through the array only once so time complexity will be O(n).

What is your favorite way and why? Let us know in the comments.

Did you find this article valuable?

Support Kannan by becoming a sponsor. Any amount is appreciated!