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
// Create an array containing duplicate itemsconst duplcateArray = [Â Â Â Â 2, 3, 4, 8, 8, 9, 9, 4, 2, Â Â Â Â 3, 3, 4, 6, 7, 5, 32, 3, 4, 5];Â
// Use Set and Spread Operator to remove // duplicate items from an arrayconsole.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
// Declare first arrayconst arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];Â
// Declare second arrayconst arr2 = [7, 8, 9, 10, 6, 11, 12, 13];Â
// Function to get the unique values array// from two arraysfunction uniqueArray(arr1, arr2) {Â Â Â Â const set = new Set(arr1.concat(arr2));Â Â Â Â return Array.from(set);}Â
// Display the array containing// unique valuesconsole.log(uniqueArray(arr1, arr2)); |
[ 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
// Create first setlet a = new Set([1, 2, 3]);Â
// Create second setlet b = new Set([4, 3, 2]);Â
// Use spread Operation to Merge both// set and then use Set() constructor// to get union of both setlet union = new Set([...a, ...b]);Â
// Display the resultconsole.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
// Create first setlet a = new Set([1, 2, 3]);Â
// Create second setlet b = new Set([4, 3, 2]);Â
// Get the instersection of both setlet intersection = new Set(Â Â Â Â [...a].filter(x => b.has(x)));Â
// Display the resultconsole.log(intersection) |
Set(2) { 2, 3 }
