DEV Community

Cover image for A Guide to : Set and Map
Abhijeet kumar
Abhijeet kumar

Posted on

A Guide to : Set and Map

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 β€”

  1. 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'} 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

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'}
Enter fullscreen mode Exit fullscreen mode

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()) // { }
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

Iteration of Set

  1. 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);
});
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Real life use case of Set in JS β€”

  1. 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.

  2. 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.

  3. 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.

  4. **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.

  5. **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.

  6. **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.

  7. 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.

  8. 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.

  9. 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.

  10. 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 β€”

  1. set( )

Adds or updates a key-value pair in the Map .

const mapDs = new Map()
mapDs.set(1 , "apple 🍎🍏")

console.log(mapDs) // 
Enter fullscreen mode Exit fullscreen mode

2. get( )

Retrieves the value associated with the specified key.

const mapDs = new Map()
mapDs.set(1 , "apple 🍎🍏")

console.log(mapDs.get(1)) // "apple 🍎🍏"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Real life use case of Map in JS β€”

  1. **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.

  2. **Routing and Navigation: **Use Maps to store routes with locations as keys and corresponding route information (distance, waypoints, etc.) as values.

  3. Caching and Memoization: Cache frequently accessed data or function results, improving performance by storing computed results with input parameters as keys.

  4. Language Localization: Store translations for different languages, with language keys and corresponding translated strings as values.

  5. 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.

  6. Event Handling: Manage event listeners by storing event types as keys and associated event handler functions as values.

  7. **Data Processing Pipelines: **Use Maps to store intermediate results in data processing pipelines, with keys representing stages or steps and values containing processed data.

  8. 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.

Top comments (0)