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 items const 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 array 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
// Declare first array const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Declare second array const arr2 = [7, 8, 9, 10, 6, 11, 12, 13]; // Function to get the unique values array // from two arrays function uniqueArray(arr1, arr2) { const set = new Set(arr1.concat(arr2)); return Array.from(set); } // Display the array containing // unique values console.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 set let a = new Set([1, 2, 3]); // Create second set let b = new Set([4, 3, 2]); // Use spread Operation to Merge both // set and then use Set() constructor // to get union of both set let union = new Set([...a, ...b]); // Display the result 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
// Create first set let a = new Set([1, 2, 3]); // Create second set let b = new Set([4, 3, 2]); // Get the instersection of both set let intersection = new Set( [...a].filter(x => b.has(x))); // Display the result console.log(intersection) |
Set(2) { 2, 3 }