In this article, we are going to see how we can create a Non-duplicated Collection using set. So in JavaScript we usually work with array, right? And we know that array can consist of duplicate value. Creating an array of values without duplicating a value takes a bit of work. You need to check each new value. ES6 provides an easier way of doing that by creating a set.
Create a Non-duplicated Collection: Using Set
Set is similar to an array which can be used to store data, but set becomes different when it comes to duplicate values. An array can have duplicate values, on which we can perform some logic to make it duplicate free. But does not take value which are already present in the set. Let’s take an example to understand:
As we can see, in the above example we have made a blank set using Set(), and we added some values using add() method. In this set, we have added 3 values, and if we try to add the same value which is already presented in the set, that value won’t get added in the set.
Now, what if we already have an array with duplicate values? Let’s see how we can make a set without duplicate values.
As you can see, we have made an array with duplicate values, and now we can pass this array in Set() while creating a set. This will simply make a set which have unique values. You can also convert this set back to array, you can pass this set to array with spread operator.
Create a Non-duplicated Collection: Iterate Through Set
Okay, we know that we can access every value using some simple logic and loop. To access every value in the set, we can use the forEach() method. forEach() method helps us to iterate through the set, it takes a callback function to do some operation related to the set’s values.
In the below example, we have created a set with an array of duplicate values and defined a sum variable. Now we applied the forEach() method on the set, in which we added a function in which we are just adding all values greater than two.
let col = new Set([1,2,3,4,5,2,3,5,2,6]),
sum = 0;
col.forEach(function(val){
if(val>2){
sum += val;
}
})
console.log(col);
console.log(sum);