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.
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