A Guide to : Set and Map
Abhijeet kumar
Posted on March 9, 2024
Hello dev π,
In this blog, weβll thoroughly discuss JavaScript Set and Map, explaining their advantages and practical uses.
Then, weβll cover detailed explanations of Set, Map and finally, weβll look into its in-build function with example.
Letβs get start β
Set βThe Set data structure is essential in JavaScript for maintaining collections of unique data, regardless of their type whether strings numbers, objects, or any other and provide various kind of inbuild function to perform various type operation with data using set.
Now let see its inbuild function β
- add( )
The add method is used with the Set data structure to add new elements to the set. This method ensures that only unique elements are added, preventing duplicates within the set. Here's how it works:
const team = new Set()
team.add('Airospace')
team.add('R&D') // will not added
console.log(team) // { 'Airospace'}
3. has( )
The has method is used to check provided values is exited in current set if the value is already existing at those time its return true otherwise its return false.
const team = new Set()
team.add('Airospace')
team.add('R&D')
console.log(team.has("Airospace")); //true
console.log(team.delete("Scientist")); // false
4. difference( )
The difference() method of Set instances takes another set as an argument and returns a new set containing elements that are present in this set but not in the given set. ( new, supported in few browser )
const a = new Set([1, 3, 5, 7, 9]);
const b= new Set([1, 4, 9]);
console.log(a.difference(b)); // Set(3) { 3, 5, 7 }
5. Intersection( )
its return new Set object containing elements in both this set and the other set. ( new, supported in few browser )
const a= new Set([1, 3, 5, 7, 9]);
const b= new Set([1, 4, 9]);
console.log(a.intersection(b)); // Set(2) { 1, 9 }
6. isDisjointFrom( )
The isDisjointFrom() method of Set instances takes another set as an argument and returns a boolean value indicating whether this set has no elements in common with the given set. ( new, supported in few browser )
const a= new Set([2, 3, 5, 7, 11, 13, 17, 19]);
const b= new Set([1, 4, 9, 16]);
console.log(a.isDisjointFrom(b)); // true
7. isSubsetOf( )
The isSubsetOf() method of Set instances takes another set as an argument and returns a boolean value indicating whether all elements of this set are also present in the given set. ( new, supported in few browser )
const a= new Set([4, 8, 12, 16]);
const b = new Set([2, 4, 6, 8, 10, 12, 14, 16, 18]);
console.log(a.isSubsetOf(b)); // true
8. isSupersetOf( )
The isSupersetOf() method of Set instances takes another set as an argument and returns a boolean value indicating whether all elements of the given set are also present in this set. ( new, supported in few browser )
const a= new Set([2, 4, 6, 8, 10, 12, 14, 16, 18]);
const b= new Set([4, 8, 12, 16]);
console.log(evens.isSupersetOf(b)); // true
8. symmetricDifference( )
The symmetricDifference() method of Set instances takes another set as an argument and returns a new set containing elements that are present in either this set or the given set, but not in both. ( new, supported in few browser )
const a= new Set([2, 4, 6, 8]);
const b= new Set([1, 4, 9]);
console.log(a.symmetricDifference(b)); // Set(5) { 1, 2, 6, 8, 9 }
9.union( )
The union() method of Set instances takes another set as an argument and returns a new set containing elements that are present in either this set or the given set, or both. ( new, supported in few browser )
const a = new Set([2, 4, 6, 8]);
const b= new Set([1, 4, 9]);
console.log(a.union(b)); // Set(6) { 2, 4, 6, 8, 1, 9 }
10. delete( )
The remove method is used to delete the existing value from the set if the value is not existing then its return false otherwise its return true after deletion of provided value.
const team = new Set()
team.add('Airospace')
team.add('R&D')
team.delete('R&D')
console.log(team) // {'Airospace'}
11. clear( )
The clear() method removes all elements from the set, effectively making it empty.
const team = new Set()
team.add('Airospace')
team.add('R&D')
console.log(team.clear()) // { }
12. size
The size property of a Set object returns the number of elements in the set. It provides a convenient way to determine the size of the set without needing to iterate over its elements manually.
const team = new Set()
team.add('Airospace')
team.add('R&D')
console.log(team.size) // 2
Iteration of Set
-
Using forEach() method: The forEach() method allows you to execute a provided function once for each element in the Set in insertion order.
const mySet = new Set(["apple π", "banana π", "orange π"]);
mySet.forEach(element => {
console.log(element);
});
2. Using a for...of loop: The for...of loop iterates over the values of an iterable object (like Set) in insertion order.
const mySet = new Set(["apple π", "banana π", "orange π"]);
mySet.forEach(element => {
console.log(element);
});
3. Converting to an array: You can convert the Set to an array using the Array.from() method or the spread operator (...) and then iterate over the array using any array iteration method (forEach(), map(), for...of, etc.).
const mySet = new Set(["apple π", "banana π", "orange π"]);
const myArray = Array.from(mySet);
myArray.forEach(element => {
console.log(element);
});
4. Using the entries, keys, or values iterator: Although Sets donβt have direct methods like keys() or entries(), you can use the iterator methods inherited from Map, but keep in mind that they would behave similarly to values() because sets don't have keys.
const mySet = new Set(["apple π", "banana π", "orange π"]);
const setIterator = mySet.values();
for (const value of setIterator) {
console.log(value);
}
Real life use case of Set in JS β
Shopping Cart Items: In an e-commerce application, a Set can be used to store unique items in a user's shopping cart. This prevents duplicate entries and ensures efficient management of the cart.
Social Media Followers/Friends List: When developing a social media platform, you might use a Set to manage a user's list of followers or friends. This ensures that each user is only added once, preventing duplicates.
User Preferences/Settings: Sets can be utilized to store unique user preferences or settings in web applications. For instance, you can use a set to manage a userβs selected language options or notification preferences.
**Event Registrations: **When managing event registrations or RSVPs, a Set can be employed to store unique attendee IDs or email addresses. This helps in ensuring that each participant is registered only once.
**Browser Cookies: **In web development, sets can aid in managing browser cookies efficiently. You can use a set to store unique cookie names, ensuring that each cookie is set only once per session.
**Search History: **Sets can be useful for managing a userβs search history in a web application. By using a set, you can ensure that each search query is stored only once, preventing duplicate entries.
Favorite Items/Bookmarks: When implementing a feature for users to bookmark favorite items or content, a Set can be employed to store unique identifiers or URLs. This ensures that each item is bookmarked only once.
User Permissions/Roles: Sets can be used to manage user permissions or roles in an application. You can use a set to store unique permission levels assigned to each user, ensuring that each permission is granted only once.
Quiz/Questionnaire Responses: When collecting responses to quizzes or questionnaires, sets can help in storing unique user answers. This prevents duplicate submissions and ensures accurate analysis of responses.
Email Subscription Lists: Sets can be utilized to manage email subscription lists for newsletters or updates. By using a set, you can ensure that each email address is subscribed only once, avoiding duplicate subscriptions.
Absolutely, the use cases for sets are diverse and depend on specific requirements.
**Map β **JavaScript, a Map is an object that stores key-value pairs while maintaining the original insertion order of the keys. Notably, Maps allow us to use both primitive and non-primitive data as keys.
Let βs see its inbuild functions β
- set( )
Adds or updates a key-value pair in the Map .
const mapDs = new Map()
mapDs.set(1 , "apple ππ")
console.log(mapDs) //
2. get( )
Retrieves the value associated with the specified key.
const mapDs = new Map()
mapDs.set(1 , "apple ππ")
console.log(mapDs.get(1)) // "apple ππ"
3. delete( )
Removes the key-value pair associated with the specified key and return true otherwise if those item is not exits then return false.
const mapDs = new Map()
mapDs.set(1 , "apple ππ")
console.log(mapDs.delete(1)) // true
4. has( )
Checks if a key exists in the Map and if exite then return true otherwise false.
const mapDs = new Map()
mapDs.set(1 , "apple ππ")
console.log(mapDs.has(1)) // true
5. clear( )
Removes all key-value pairs from the Map and return true after deletion of all item from Map.
const mapDs = new Map()
mapDs.set(1 , "apple ππ")
console.log(mapDs.clear()) // true
Iterating Over a Map:
Maps in JavaScript preserve the insertion order of key-value pairs, making them ideal for scenarios where order matters. You can iterate over the keys, values, or entries (key-value pairs) of a Map using various methods like forEach, for...of loop, or entries, keys, and values methods.
// Iterating over keys
for (let key of myMap.keys()) {
console.log(key);
}
// Iterating over values
for (let value of myMap.values()) {
console.log(value);
}
// Iterating over entries
for (let [key, value] of myMap.entries()) {
console.log(key, value);
}
Real life use case of Map in JS β
**User Authentication and Authorization: **Store user information with usernames or user IDs as keys and user objects (containing details like username, password hash, access level) as values.
**Routing and Navigation: **Use Maps to store routes with locations as keys and corresponding route information (distance, waypoints, etc.) as values.
Caching and Memoization: Cache frequently accessed data or function results, improving performance by storing computed results with input parameters as keys.
Language Localization: Store translations for different languages, with language keys and corresponding translated strings as values.
Error Handling and Logging: Track error occurrences with error codes or descriptions as keys and additional error details as values, facilitating error reporting and debugging.
Event Handling: Manage event listeners by storing event types as keys and associated event handler functions as values.
**Data Processing Pipelines: **Use Maps to store intermediate results in data processing pipelines, with keys representing stages or steps and values containing processed data.
Form Data Handling: Store form field names as keys and corresponding input values as values, simplifying form data manipulation and validation.
These are just a few real-life use cases of Maps in JavaScript; however, the full extent of their application is not limited and wholly depends on the requirements at hand.
Conclusion β Overall, Sets and Maps are versatile data structures that can greatly simplify your code and improve the efficiency of your applications. Whether youβre managing collections of unique elements or associating data with keys, Sets and Maps provide essential tools for working with data in JavaScript.
Posted on March 9, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.