Maps and sets in Javascript
Before we get into conversions, let's understand why we have Maps and Sets in the first place. JavaScript developers traditionally use objects and arrays to store data, but these structures come with their own limitations:
- Objects: Good for keyed collections, but restrict keys to strings or symbols.
- Arrays: Useful for ordered collections but allow duplicate entries and rely on numerical indices.
In many real-world scenarios, you need more flexible or unique data management, and that’s where Maps and Sets step in.
Map
A Map is a collection of keyed data items, similar to an object. However, the key difference (pun intended) is that in a Map, keys can be any type, not just strings. This means you can use objects, functions, and other data types as keys in a Map.
Key Features of Map:
new Map()
: Creates a new Map.map.set(key, value)
: Adds a key-value pair to the Map.map.get(key)
: Retrieves the value associated with the key.map.has(key)
: Checks if a key exists.map.delete(key)
: Removes a key-value pair.map.clear()
: Removes all entries from the Map.map.size
: Returns the number of entries in the Map.
let userVisits = new Map();
userVisits.set('John', 10);
userVisits.set('Jane', 15);
userVisits.set(123, 'Special ID');
console.log(userVisits.get('John')); // 10
console.log(userVisits.get(123)); // 'Special ID'
One of the biggest strengths of a Map is that you can use non-string keys. Unlike objects, which convert everything to a string, a Map preserves the actual type.
Use Case:
Let's say you're building a social media app, and you want to keep track of how many times a user (represented as an object) has visited your site. With a Map, you can use the entire user object as the key:
let john = { name: "John" };
let userVisits = new Map();
userVisits.set(john, 5);
console.log(userVisits.get(john)); // 5
Set
A Set is a special collection type that holds unique values. In other words, it ensures that there are no duplicates in the collection. This is especially useful when you need to store data that must be unique, such as user IDs, or to filter out duplicates from a list.
Key Features of Set:
new Set([iterable])
: Creates a new Set. You can pass an array or another iterable to initialize it.set.add(value)
: Adds a value to the Set. If the value already exists, it won’t be added again.set.delete(value)
: Removes a value from the Set.set.has(value)
: Checks if a value is in the Set.set.clear()
: Removes all values from the Set.set.size
: Returns the number of unique values in the Set.
let uniqueItems = new Set([1, 2, 3, 4, 1, 2]);
console.log(uniqueItems.size); // 4 (duplicates removed)
Use Case:
Imagine you're tracking visitors to a website, and you only want to count unique visitors. Every time a visitor lands on the site, you can add them to a Set, ensuring that duplicate visits are not counted.
let visitorSet = new Set();
visitorSet.add('John');
visitorSet.add('Jane');
visitorSet.add('John'); // Duplicate visit won't be added
console.log(visitorSet.size); // 2
Converting Between Maps and Sets
Now that we have a clear understanding of Maps and Sets, let’s get into how we can convert between these two data structures.
Conversion from Map to Set
Sometimes, you might have a Map where you only care about the keys or the values, and you want to ensure that they’re unique. This is where converting a Map to a Set comes into play.
- Extracting Keys into a Set: You can extract the keys from a Map and store them in a Set. This ensures that all keys are unique, and you can perform Set operations like checking for the existence of certain keys.
let userScores = new Map([
['Alice', 85],
['Bob', 90],
['Charlie', 78]
]);
let uniqueUsers = new Set(userScores.keys());
console.log(uniqueUsers); // Set {'Alice', 'Bob', 'Charlie'}
- Extracting Values into a Set: Similarly, you might only be interested in the unique values stored in a Map, in which case you can convert them into a Set.
let userScores = new Map([
['Alice', 85],
['Bob', 90],
['Charlie', 85] // Duplicate score
]);
let uniqueScores = new Set(userScores.values());
console.log(uniqueScores); // Set {85, 90}
Conversion from Set to Map
Although Sets don’t store key-value pairs, they can still be converted to Maps if you want to associate each element of a Set with a value.
- Convert a Set to a Map with the Same Value: A common use case is when you want to initialize a Map with default values for each key. In this example, we convert a Set of users to a Map where each user starts with a default score of 0.
let users = new Set(['Alice', 'Bob', 'Charlie']);
let userScores = new Map();
users.forEach(user => {
userScores.set(user, 0); // Default score of 0
});
console.log(userScores); // Map { 'Alice' => 0, 'Bob' => 0, 'Charlie' => 0 }
- Converting a Set to a Map Using Index: Another approach is to use the index of the Set elements as keys. This is helpful when you need an ordered association.
let items = new Set(['apple', 'banana', 'cherry']);
let itemMap = new Map();
Array.from(items).forEach((item, index) => {
itemMap.set(index, item);
});
console.log(itemMap); // Map { 0 => 'apple', 1 => 'banana', 2 => 'cherry' }
Object and Array Conversions with Maps and Sets
Maps and Sets can also be converted to and from objects and arrays, making them incredibly versatile.
Convert a Map to an Object:
Using Object.fromEntries()
, you can convert a Map back to a plain object.
let pricesMap = new Map([
['banana', 1],
['apple', 2],
['pear', 3]
]);
let pricesObj = Object.fromEntries(pricesMap);
console.log(pricesObj); // {banana: 1, apple: 2, pear: 3}
Convert an Object to a Map:
You can use Object.entries()
to convert a regular object into a Map:
let userObj = {
name: 'John',
age: 30
};
let userMap = new Map(Object.entries(userObj));
console.log(userMap); // Map { 'name' => 'John', 'age' => 30 }
Convert a Set to an Array:
This is straightforward using the spread operator (...
), or Array.from()
:
let uniqueFruits = new Set(['apple', 'banana', 'orange']);
let fruitArray = [...uniqueFruits]; // ['apple', 'banana', 'orange']
Convert an Array to a Set:
Likewise, you can easily convert an array to a Set:
let numbers = [1, 2, 3, 4, 4, 5];
let uniqueNumbers = new Set(numbers); // Set {1, 2, 3, 4, 5}
Filtering Duplicates from an Array
Let’s consider a real-life scenario where you have a list of values that may contain duplicates, and you want to filter out these duplicates.
You can use a Set to accomplish this, as a Set automatically eliminates duplicate entries.
function uniqueArray(arr) {
return [...new Set(arr)];
}
let values = ["apple", "banana", "apple", "orange", "banana"];
let uniqueValues = uniqueArray(values);
console.log(uniqueValues); // ['apple', 'banana', 'orange']
Conclusion
JavaScript's Maps and Sets offer powerful, flexible alternatives to traditional objects and arrays. Whether you're managing unique data sets or need more flexible key-value pairs, these structures allow you to write more efficient, cleaner code. By understanding how to convert between them, you got yourself a tool that will come in handy in real-life scenarios.
Now that you are all "set", let's proceed!