The new Set object from the ES2015 latest browser specification has a variety of use cases. In this tutorial, we will have a look at a simple scenario where we explore ways in which this feature can come in handy.
Note: Before we continue, it should be noted that the new Set object currently has good browser support and therefore can be used in production applications. If you want to have a look at the browser support or compatibility, you can take a look at it here.
According to the MDN documentation, the Set object allows you store unique values of any type, whether they are primitive data types like strings, booleans, symbols, null, etc or even objects.
Below is an example of the syntax of the new Set object,
new Set([iterable])
In this example, the parameter is iterable - which is more like an object or a collection that we can loop through. A simple example of an iterable is an array.
Note: When values are passed to the Set object, they always remain unique and a new Set object is always returned. On the other hand, if nothing is passed to the Set object or if its value is a primitive like null for example, its return value will be empty.
Moving on, just like every object has a constructor function, where they derive their traits from including methods and properties, all instances of the Set object inherit from the Set prototype. Therefore, the Set.prototype.constructor is the function that gets returned when an instance prototype is created. Remember when you use the "new" keyword to declare an instance of something? Great!
Now looking at some of the properties and methods available on the Set prototype, we have the Set.prototype.size, which returns the number of values in the Set object. Additionally, we also have the Set.prototype.add() method which as the name implies, adds a new element with the given value to the Set object and returns the new Set object.
Now lets look at a simple example,
var myNewSet = new Set();
myNewSet.add(1)
// returns Set [1]
myNewSet.add(5);
// returns Set [ 1, 5 ]
myNewSet.add(5);
// returns Set [ 1, 5 ]
Here, we have declared a variable myNewSet which stores a new instance of the Set object in memory. We then used the add method to populate the variable. We will notice that the last returned Set object has just a single value of "5" instead of two as expected. Well, this exactly validates our initial point that the values in a Set object may only occur once since it is unique in the Set's collection.
Note: Earlier we mentioned that to check the number of values in the Set object, we should make use of the Set.prototype.size property. The Set.prototype.length property does not check the number of values in a Set object as expected but instead returns 0 which is the value of the length property in this case.
Another example of applying the new Set object is in the case of removing array duplicates. let's take a look at an example,
const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]
console.log([...new Set(numbers)])
// [2, 3, 4, 5, 6, 7, 32]
We can see here that the duplicates were flushed out of the array and a new array was returned with unique elements only. Before now, we had to loop through the array and do a bunch of gymnastics to remove the duplicates. With the new Set method, we saw how we intuitively and with lesser lines of code achieved our aim.
Now to the more interesting part before we conclude, I was going through a short excerpt on Graphql, where I came across another pretty nifty and important use case of the Set object. Let's look at the example because I believe examples help communicate intent more,
var distances = [
{ from: "Tahoe City", to: "Nevada City", distance: 65 },
{ from: "Nevada City", to: "Redwood Valley", distance: 151 },
{ from: "Redwood Valley", to: "Willits", distance: 16 },
{ from: "Willits", to: "Garberville", distance: 68 },
{ from: "Garberville", to: "Shelter Cove", distance: 24 },
{ from: "Garberville", to: "Mendocino", distance: 76 },
{ from: "Mendocino", to: "Redwood Valley", distance: 51 }
];
Now the case study here is for us to look for a way to remove duplicate cities from the array of objects because we intended to query for the city data and we didn't want duplicates.
Now the implementation;
var cities = new Set();
distances.forEach(d => {
cities.add(d.from);
cities.add(d.to);
});
return Array.from(cities);
// returns (7) ["Tahoe City", "Nevada City", "Redwood Valley", "Willits", "Garberville", "Shelter Cove", "Mendocino"]
Here, first of all, we declared a new instance of the Set object which allows us to inherit from the prototype of the object - its methods and properties. We then looped through the array of objects stored in the distance variable, and for each iteration, we appended the cities to the Set object while removing duplicates in the process.
We can now see a simple and very useful example where the Set object comes in handy. Also, note the use of the add method? Great! Now, also notice the Array.from() method? This method creates an array from an iterable object, where the parameter must be an iterable object, so as to enable us to convert it to an array.
For more information on this method and its use cases, you can check the documentation here at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
Finally, for more information on everything good about the Set Object and for those who want to explore further, you can check the reference documentation on MDN.
Big thanks to Alex Banks and Eve Porcello and the MoonHighway team for their article, where I extracted the last example from, so as to illustrate and drive home a very vital use case. For more information, you can check them out https://moonhighway.com/.
Resources cited here are from the Mozilla developer network documentation.
Thanks for taking the time out to read this. I would really appreciate any questions, comments, and general feedback. Keep learning!
Top comments (1)
Thank you for this excellent and simple explanation of the Set object. It was a great help for me in solving a kata on Codewars today.😁😁