JS ES6 Two New DS
In this article, you’re going to learn Set and Map data structure in JS
ES6 included two data structures that help programmers get work done without reinventing the wheel. These two data structures are Set and Map.
If you remember math from your school you may understand the purpose of the set in math if you do that’s right in JS Set has the ideal purpose as math does.
In math set doesn’t accept repetitive numbers as well as in JS set is similar to an array but with one difference is that set doesn't allow repeated values if we add repeated item in a set then it automatically removes that item.
We create set by using Set constructor if you know classes or Constructor functions in JS you have to know what’s function constructor. when we create an instance of class or an instance object or and functional constructor we use new keyword the new keyword tells that create another instance of this object.
Set- The set object allows you to store unique values of any type
set has many methods that we can use for example we can item in a set by using set.add(item), deleting item from a set -> set.delete(item) or remove all items from a set by using set.clear().
we can add items in a set on its own place for example.
if I want to add pomegranate into my fruits set then I use add() method.
If you want to delete one of item in your fruits set you can remove it through the delete(item) method.
Some Useful Set Methods
we can add more items to a Set using add() method. this method adds a new value to the Set object and returns the Set. An attempt to add a duplicate value to the set object wouldn’t return an error,instead,the item will not be added.
we can remove more items from a Set object using delete() method. if the preferred item isn’t available in the Set returns false else return true.
we can delete individual item using delete() method if you want to delete whole items from a Set use clear() method this method clears all items from a Set object.
delete() removes individual item.
clear() method removes all items from a Set
Size of a Set
We can get the size of a Set using size() property on the Set prototype. This is similar to the length() property for Arrays.
Searching for items
We may need to know if a Set has a particular item. This can be accomplished using has() method. The has() method returns true if the item is in the Set object, and false if it isn’t.
Returning the Items in a Set
We can return the items in a Set object in the same insertion order using the values() method. This method returns a new setIterator object. A similar method for returning the items in a set using keys() method.
The whole code ⬇