How to use Sets In Javascript
To print unique elements from two unsorted arrays in JavaScript using Sets, combine the arrays into a Set, then convert the Set back into an array. This ensures that duplicate elements are removed automatically, providing the unique elements.
Example: In this example we creates sets from arr1 and arr2, filters out items unique to each set, and combines them into a single array unique. It logs the array containing unique elements from both arrays.
const arr1 = [54, 71, 58, 95, 20];
const arr2 = [71, 51, 54, 33, 80];
const set1 = new Set(arr1);
const set2 = new Set(arr2);
const unique1 = arr1.filter(item => !set2.has(item));
const unique2 = arr2.filter(item => !set1.has(item));
const unique = [...unique1, ...unique2];
console.log(unique);
Output
[ 58, 95, 20, 51, 33, 80 ]
How to print unique elements from two unsorted arrays using JavaScript ?
Given two unsorted arrays, the task is to write a JavaScript program to print the unique (uncommon) elements in the two arrays.
These are the way by which we print unique elements from two unsorted arrays using JavaScript:
Table of Content
- Using for loop
- Using filter() method
- Using Sets