Map
and Set
are two important data structures introduced in ES6 that provide efficient ways to manage collections of data. Each serves distinct purposes and offers unique benefits over traditional data structures like objects and arrays. Here’s a practical look at how and why you might use them:
Map, what it is
- A
Map
is a collection of key-value pairs where both keys and values can be of any type. - Unlike objects, which use strings or symbols as keys,
Map
allows for any data type as a key (e.g., objects, functions, primitive types).
Practical Uses of Map:
- Storing and Retrieving Data with Any Key Type:
- Use
Map
when you need to use objects or other non-primitive values as keys.
const map = new Map();
const keyObject = {};
map.set(keyObject, 'value associated with an object key');
console.log(map.get(keyObject)); // value associated with an object key
- Maintaining Insertion Order:
Map
maintains the order of elements based on their insertion. This can be useful when you need to iterate over keys and values in the order they were added.
const map = new Map();
map.set('first', 1);
map.set('second', 2);
map.set('third', 3);
for (const [key, value] of map) {
console.log(`${key}: ${value}`);
}
// Output:
// first: 1
// second: 2
// third: 3
- Efficient Lookups:
Map
provides O(1) time complexity for operations such asset
,get
, andhas
. This makes it efficient for scenarios where you frequently look up values by their keys.
const map = new Map();
map.set('key1', 'value1');
console.log(map.has('key1')); // true
- Dynamic Key Management:
Map
is particularly useful when dealing with dynamic key-value pairs, such as when working with data from an API or a configuration object.
const userMap = new Map();
userMap.set('user1', { name: 'Alice', age: 30 });
userMap.set('user2', { name: 'Bob', age: 25 });
Set: What is a Set
- A
Set
is a collection of unique values. It does not allow duplicate entries, and values are stored in insertion order. - Unlike arrays, which can contain duplicates,
Set
ensures that each value appears only once.
Practical Uses of Set:
- Unique Values:
- Use
Set
when you need to ensure that a collection contains only unique values.
const set = new Set();
set.add(1);
set.add(2);
set.add(2); // Duplicate value, will not be added
console.log(set); // Set { 1, 2 }
- Efficient Membership Testing:
Set
provides O(1) time complexity for membership tests (has
) and insertion operations (add
), making it efficient for operations that require checking for duplicates or the existence of an item.
const set = new Set([1, 2, 3, 4]);
console.log(set.has(3)); // true
console.log(set.has(5)); // false
- Removing Duplicates from Arrays:
- Use
Set
to easily remove duplicates from an array.
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]
- Iterating Over Unique Values:
Set
can be used to iterate over unique values in insertion order, which is useful when you need to process each item exactly once.
const set = new Set(['a', 'b', 'c']);
for (const value of set) {
console.log(value);
}
// Output:
// a
// b
// c
Summary
- Use
Map
when you need a key-value store with keys that can be of any data type and when you require insertion order or efficient lookups. - Use
Set
when you need a collection of unique values, efficient membership testing, or to remove duplicates from an array.
Both Map
and Set
are versatile and powerful tools in modern JavaScript development, helping to manage and manipulate collections of data efficiently.