Applications of Set in JavaScript
Last Updated :
01 Aug, 2023
A Set is a collection of items that are unique i.e. no element can be repeated. Set in ES6 are ordered: elements of the set can be iterated in the insertion order. The set can store any type of value whether primitive or objects.
Application of Set in JavaScript:
- Deleting duplicates element from an array
- Creating a unique array from the unique values of two arrays
- Union of two sets
- Interaction of two sets
Approach 1: Deleting duplicates element from an array
In this approach, we are given a set with multiple duplicate values and we will remove the duplicates from the set.
Example:
Javascript
const duplcateArray = [
2, 3, 4, 8, 8, 9, 9, 4, 2,
3, 3, 4, 6, 7, 5, 32, 3, 4, 5
];
console.log([... new Set(duplcateArray)]);
|
Output:
[ 2, 3, 4, 8, 9, 6, 7, 5, 32 ]
Approach 2: Creating a unique array from the unique values of two arrays
In this approach, we will create a unique array from the unique value of two arrays.
Example:
Javascript
const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const arr2 = [7, 8, 9, 10, 6, 11, 12, 13];
function uniqueArray(arr1, arr2) {
const set = new Set(arr1.concat(arr2));
return Array.from(set);
}
console.log(uniqueArray(arr1, arr2));
|
Output
[
1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12,
13
]
Approach 3: Union of two sets
In this approach, we will join the values of two sets
Example:
Javascript
let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
let union = new Set([...a, ...b]);
console.log(union)
|
Output:
{ 1, 2, 3, 4 }
Approach 4: Interaction of two sets
In this approach, we will get the intersection of two sets.
Example:
Javascript
let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
let intersection = new Set(
[...a].filter(x => b.has(x)));
console.log(intersection)
|
Share your thoughts in the comments
Please Login to comment...