How to use Set and filter In Javascript

To filter out non-unique values using Set and filter, first use filter to find items whose first and last occurrences match. Then convert the result to a Set to ensure uniqueness. Finally, convert the Set back to an array.

Syntax:

const uniqueItems = new Set(arr.filter(item => 
arr.indexOf(item) === arr.lastIndexOf(item)));

Example: In this example the function filters non-unique elements from an array using a Set, comparing first and last index occurrences, then returns the unique items.

JavaScript
function filterNonUniqueUsingSet(arr) {
    const uniqueItems = new Set(arr.filter(item => 
    arr.indexOf(item) === arr.lastIndexOf(item)));
    return [...uniqueItems];
}

const array = [1, 2, 2, 3, 4, 4, 5];
console.log(filterNonUniqueUsingSet(array));

Output
[ 1, 3, 5 ]

How to filter out the non-unique values in an array using JavaScript ?

In JavaScript, arrays are the object using the index as the key of values. In this article, let us see how we can filter out all the non-unique values and in return get all the unique and non-repeating elements.

These are the following ways by which we can filter out the non-unique values in an array:

Table of Content

  • Using the filter() method
  • Using for loop
  • Using Set and filter
  • Using the reduce() Method

Similar Reads

Using the filter() method

The filter() method returns the array of elements that satisfy the condition that the first occurrence index and last occurrence index must be the same for a unique element. We use the indexOf() method to get the index first occurrence of an element and the lastIndexOf() method to get the last occurrence of an element....

Using for loop

In the for loop, we only push our unique elements into the array, if it satisfies the condition that the first occurrence index and last occurrence index must be the same. We use the indexOf() method to get the index first occurrence of an element and the lastIndexOf() method to get the last occurrence of an element....

Using Set and filter

To filter out non-unique values using Set and filter, first use filter to find items whose first and last occurrences match. Then convert the result to a Set to ensure uniqueness. Finally, convert the Set back to an array....

Using the reduce() Method

The reduce() method can be used to create a frequency map of the elements in the array. Once we have this map, we can filter out the elements that appear only once....

Contact Us