Skip to main content

Exploring Maps and Sets in JavaScript: ES6 Collections Made Easy

ยท 10 min read

"Exploring Maps and Sets in JavaScript: ES6 Collections Made Easy"

Introductionโ€‹

ES6 introduced two powerful data structures, Maps and Sets, that provide enhanced ways to manage and manipulate data in JavaScript.

Maps offer key-value pair storage, while Sets store unique values without duplicates.

In this guide, we'll explore the concepts of Maps and Sets and see how they can simplify various programming tasks.

Suggested Tutorials ๐Ÿ“‘:โ€‹

1. What are Maps?โ€‹

Maps are a new data structure in ES6 that allow you to store key-value pairs.

Maps are similar to objects in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key.

However, there are some important differences that make Maps preferable in certain cases.

1.1. Creating Mapsโ€‹

Maps are created using the Map() constructor:

const map = new Map();

You can also pass an array of key-value pairs to the Map() constructor:

const map = new Map([
['key1', 'value1'],
['key2', 'value2']
]);

1.2. Adding and Retrieving Valuesโ€‹

You can add values to a Map using the set() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

You can retrieve values from a Map using the get() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

console.log(map.get('key1')); // value1
console.log(map.get('key2')); // value2

Suggested Tutorials ๐Ÿ“‘:โ€‹

1.3. Checking for Valuesโ€‹

You can check whether a Map contains a value using the has() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

console.log(map.has('key1')); // true
console.log(map.has('key2')); // true
console.log(map.has('key3')); // false

1.4. Deleting Valuesโ€‹

You can delete values from a Map using the delete() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

map.delete('key1');
console.log(map.has('key1')); // false

1.5. Getting the Size of a Mapโ€‹

You can get the size of a Map using the size property:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

console.log(map.size); // 2

Suggested Tutorials ๐Ÿ“‘:โ€‹

1.6. Iterating Over Mapsโ€‹

You can iterate over a Map using the for...of loop:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

for (const [key, value] of map) {
console.log(`${key} = ${value}`); // key1 = value1, key2 = value2
}

You can also iterate over a Map using the forEach() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

forEach((value, key) => {
console.log(`${key} = ${value}`); // key1 = value1, key2 = value2
});

1.7. Converting Maps to Arraysโ€‹

You can convert a Map to an array using the Array.from() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

const array = Array.from(map);
console.log(array); // [ ['key1', 'value1'], ['key2', 'value2'] ]

1.8. Converting Maps to Objectsโ€‹

You can convert a Map to an object using the Object.fromEntries() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

const object = Object.fromEntries(map);
console.log(object); // { key1: 'value1', key2: 'value2' }

Suggested Tutorials ๐Ÿ“‘:โ€‹

1.9. Converting Objects to Mapsโ€‹

You can convert an object to a Map using the Object.entries() method:

const object = { key1: 'value1', key2: 'value2' };
const map = new Map(Object.entries(object));
console.log(map); // Map { 'key1' => 'value1', 'key2' => 'value2' }

1.10. Converting Maps to JSONโ€‹

You can convert a Map to JSON using the JSON.stringify() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

const json = JSON.stringify([...map]);
console.log(json); // [["key1","value1"],["key2","value2"]]

1.11. Converting JSON to Mapsโ€‹

You can convert JSON to a Map using the JSON.parse() method:

const json = '[["key1","value1"],["key2","value2"]]';
const map = new Map(JSON.parse(json));
console.log(map); // Map { 'key1' => 'value1', 'key2' => 'value2' }

1.12. Cloning Mapsโ€‹

You can clone a Map using the Map() constructor:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

const clone = new Map(map);
console.log(clone); // Map { 'key1' => 'value1', 'key2' => 'value2' }

1.13. Filtering Mapsโ€‹

You can filter a Map using the Map() constructor and the Array.from() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
map.set('key3', 'value3');
map.set('key4', 'value4');

const filtered = new Map(Array.from(map).filter(([key, value]) => key === 'key1' || key === 'key2'));

console.log(filtered); // Map { 'key1' => 'value1', 'key2' => 'value2' }

Suggested Tutorials ๐Ÿ“‘:โ€‹

2. Differences between Maps and Objectsโ€‹

Here are some of the key differences between Maps and objects:

  • The keys of an object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
  • You can get the size of a Map easily with the size property, while the number of properties in an object must be determined manually.
  • A Map is an iterable and can thus be directly iterated, whereas iterating over an object requires obtaining its keys in some fashion and iterating over them.
  • An Object has a prototype, so there are default keys in the map that could collide with your keys if you're not careful. As of ES5 this can be bypassed by using map = Object.create(null), but this is seldom done.
  • A Map may perform better in scenarios involving frequent addition and removal of key pairs.

3. What are Sets?โ€‹

Sets are a new data structure in ES6 that allow you to store unique values without duplicates.

Sets are similar to arrays in that both let you store values, retrieve those values, delete values, and detect whether something is stored in a set.

However, there are some important differences that make Sets preferable in certain cases.

3.1. Creating Setsโ€‹

Sets are created using the Set() constructor:

const set = new Set();

You can also pass an array of values to the Set() constructor:

const set = new Set(['value1', 'value2']);

3.2. Adding and Retrieving Valuesโ€‹

You can add values to a Set using the add() method:

const set = new Set();
set.add('value1');
set.add('value2');

You can retrieve values from a Set using the has() method:

const set = new Set();
set.add('value1');
set.add('value2');

console.log(set.has('value1')); // true
console.log(set.has('value2')); // true
console.log(set.has('value3')); // false

Suggested Tutorials ๐Ÿ“‘:โ€‹

3.3. Checking for Valuesโ€‹

You can check whether a Set contains a value using the has() method:

const set = new Set();
set.add('value1');
set.add('value2');

console.log(set.has('value1')); // true
console.log(set.has('value2')); // true
console.log(set.has('value3')); // false

3.4. Deleting Valuesโ€‹

You can delete values from a Set using the delete() method:

const set = new Set();
set.add('value1');
set.add('value2');

set.delete('value1');
console.log(set.has('value1')); // false

3.5. Getting the Size of a Setโ€‹

You can get the size of a Set using the size property:

const set = new Set();
set.add('value1');
set.add('value2');

console.log(set.size); // 2

3.6. Iterating Over Setsโ€‹

You can iterate over a Set using the for...of loop:

const set = new Set();
set.add('value1');
set.add('value2');

for (const value of set) {
console.log(value); // value1, value2
}

You can also iterate over a Set using the forEach() method:

const set = new Set();
set.add('value1');
set.add('value2');

set.forEach(value => {
console.log(value); // value1, value2
});

3.7. Converting Sets to Arraysโ€‹

You can convert a Set to an array using the Array.from() method:

const set = new Set();
set.add('value1');
set.add('value2');

const array = Array.from(set);
console.log(array); // [ 'value1', 'value2' ]

Suggested Tutorials ๐Ÿ“‘:โ€‹

3.8. Converting Arrays to Setsโ€‹

You can convert an array to a Set using the Set() constructor:

const array = ['value1', 'value2'];
const set = new Set(array);
console.log(set); // Set { 'value1', 'value2' }

3.9. Converting Sets to JSONโ€‹

You can convert a Set to JSON using the JSON.stringify() method:

const set = new Set();
set.add('value1');
set.add('value2');

const json = JSON.stringify([...set]);
console.log(json); // ["value1","value2"]

3.10. Converting JSON to Setsโ€‹

You can convert JSON to a Set using the JSON.parse() method:

const json = '["value1","value2"]';
const set = new Set(JSON.parse(json));
console.log(set); // Set { 'value1', 'value2' }

3.11. Cloning Setsโ€‹

You can clone a Set using the Set() constructor:

const set = new Set();
set.add('value1');
set.add('value2');

const clone = new Set(set);
console.log(clone); // Set { 'value1', 'value2' }

3.12. Filtering Setsโ€‹

You can filter a Set using the Set() constructor and the Array.from() method:

const set = new Set();
set.add('value1');
set.add('value2');
set.add('value3');
set.add('value4');

const filtered = new Set(Array.from(set).filter(value => value === 'value1' || value === 'value2'));

console.log(filtered); // Set { 'value1', 'value2' }

4. Differences between Sets and Arraysโ€‹

Here are some of the key differences between Sets and arrays:

  • Sets are not indexed-based - you do not refer to items in a set based on their position in the set.
  • Items in a Set can't be accessed individually.
  • You can easily remove a value from a Set.
  • Sets are iterable, so you can directly loop over them.
  • A value in a Set occurs only once - duplicates are not allowed.
  • Sets can be combined with arrays to create new arrays that contain unique values.

Suggested Tutorials ๐Ÿ“‘:โ€‹

Conclusionโ€‹

Maps and Sets are powerful data structures that provide enhanced ways to manage and manipulate data in JavaScript.

Maps offer key-value pair storage, while Sets store unique values without duplicates.

In this guide, we explored the fundamentals of Maps and Sets and saw how they can simplify various programming tasks.

We also saw the differences between Maps and objects, and between Sets and arrays.

We hope you found this guide helpful.

Happy coding! ๐Ÿฅณ