DEV Community

Cover image for 11-ES6++: Map and Set in Javascript
Hasan Zohdy
Hasan Zohdy

Posted on

11-ES6++: Map and Set in Javascript

Map Class

Map is a new data structure introduced in ES6, it is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

const map = new Map();

map.set('name', 'Hasan'); 
map.set('age', 41);

console.log(map.get('name')); // Hasan
console.log(map.get('age')); // 41
Enter fullscreen mode Exit fullscreen mode

Well, in that sense, we just created a new instance of the Map and added two items to it, then we got the values of the items by their keys.

Iterating over Map

We can iterate over the Map using the for...of loop.

const map = new Map();

map.set('name', 'Hasan');
map.set('age', 41);

for (const [key, value] of map) {
  console.log(key, value);
}
Enter fullscreen mode Exit fullscreen mode

Passing an Array to Map

We can pass an array of arrays to the Map constructor to initialize the Map with some data.

const map = new Map([
  ['name', 'Hasan'],
  ['age', 41]
]);

console.log(map.get('name')); // Hasan
console.log(map.get('age')); // 41
Enter fullscreen mode Exit fullscreen mode

Although Map is an object-like, it can not receiver an object on the constructor.

const map = new Map({
  name: 'Hasan',
  age: 41
});

// TypeError: object is not iterable
Enter fullscreen mode Exit fullscreen mode

Map Methods

Map has many methods, here are some of them:

  • map.set(key, value) - stores the value by the key.
  • map.get(key) - returns the value by the key, undefined if key doesn't exist in map.
  • map.has(key) - returns true if the key exists, false otherwise.
  • map.delete(key) - removes the value by the key.
  • map.clear() - removes everything from the map.
  • map.size - returns number of items in the map.

Set Class

Set is a collection of unique values, just like an Array but it doesn't allow duplicates.

const set = new Set();

set.add('Hasan');
set.add('Ahmed');
set.add('Hasan');

console.log(set.size); // 2
Enter fullscreen mode Exit fullscreen mode

What happened here? as i mentioned above, Set does not allow duplicates, so when we added Hasan twice, it was added only once.

But what about objects?

const set = new Set();

set.add({ name: 'Hasan' });
set.add({ name: 'Hasan' });

console.log(set.size); // 2
Enter fullscreen mode Exit fullscreen mode

As you can see, we added two objects with the same value, but they are not equal, so they were added to the Set, why they are not equal? because objects are compared by reference, not by value.

Let's see when we add the same object twice.

const obj = { name: 'Hasan' };

const set = new Set();

set.add(obj);
set.add(obj);

console.log(set.size); // 1
Enter fullscreen mode Exit fullscreen mode

As we're adding the same object twice (Notice the same constant not a new object with same value), they are equal, so they were added only once.

Iterating over Set

We can iterate over the Set using the for...of loop.

const set = new Set();

set.add('Hasan');
set.add('Ahmed');

for (const value of set) {
  console.log(value); // Hasan, Ahmed
}
Enter fullscreen mode Exit fullscreen mode

Receiving array in the Set constructor

We can pass an Array to the Set constructor to create a Set from the Array.

const set = new Set(['Hasan', 'Ahmed']);

console.log(set.size); // 2
Enter fullscreen mode Exit fullscreen mode

Set Methods

Set has many methods, here are some of them:

  • set.add(value) - adds a value, returns the set itself.
  • set.delete(value) - removes the value.
  • set.has(value) - returns true if the value exists in the set, otherwise false.
  • set.clear() - removes everything from the set.
  • set.size - returns the number of elements in the set, (not its a property not a method).

Map VS Set

Map is a collection of key/value pairs, while Set is a collection of values.

Map allows duplicate values, but unique keys while Set does not allow duplicate values.

Map allows keys of any type, while Set does not have keys, it only has values.

Map has set method to add key/value pairs, while Set has add method to add values.

Similarities between Map and Set

Both Map and Set are iterable, so we can use for...of loop to iterate over them.

Both Map and Set have size property to get the number of elements.

Both Map and Set have clear method to remove all elements.

Both Map and Set have delete method to remove an element.

Both Map and Set have has method to check if an element exists, except that Map checks for the key is exists while Set check if the given value exists in the set.

Using Set to remove duplicate values from an array

A good practice to get unique values (Primitive values only) is by using Set to remove duplicates.

const arr = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];

const uniqueValues = [...new Set(arr)];

console.log(uniqueValues); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

However, duplicate objects/arrays that have same value (not same reference) will not be removed.

const arr = [
  { name: 'Hasan' },
  { name: 'Ahmed' },
  { name: 'Hasan' },
];

const uniqueValues = [...new Set(arr)];

console.log(uniqueValues); // [{ name: 'Hasan' }, { name: 'Ahmed' }, { name: 'Hasan' }]
Enter fullscreen mode Exit fullscreen mode

If objects or arrays are duplicated by reference, then it will be removed.

const obj = { name: 'Hasan' };

const arr = [
  obj,
  { name: 'Ahmed' },
  obj,
];

const uniqueValues = [...new Set(arr)];

console.log(uniqueValues); // [{ name: 'Hasan' }, { name: 'Ahmed' }]
Enter fullscreen mode Exit fullscreen mode

Works as well with arrays.

const arr = [
  [1, 2],
  [3, 4],
  [1, 2],
];

const uniqueValues = [...new Set(arr)];

console.log(uniqueValues); // [[1, 2], [3, 4]]
Enter fullscreen mode Exit fullscreen mode

Duplicate array values by reference are not removed

// array contains list of arrays by reference

const numbersList = [1, 2, 3, 4];

const mixedArray = [numbersList, ['a', 'b', 'c'], numbersList];

const uniqueValues = [...new Set(mixedArray)];

console.log(uniqueValues); // [[1, 2, 3, 4], ['a', 'b', 'c'], [1, 2, 3, 4]]
Enter fullscreen mode Exit fullscreen mode

๐ŸŽจ Conclusion

In this article, we learned about Map and Set classes, we learned how to create them, how to add values to them, how to iterate over them, and how to use them to remove duplicate values from an array.

We can label Set as it is a collection of unique values, and Map as it is a collection of key/value pairs.

Set is more similar to Arrays than Map is, because Set is a collection of values, while Map is a collection of key/value pairs, so it is similar to Objects.

โ˜•โ™จ๏ธ Buy me a Coffee โ™จ๏ธโ˜•

If you enjoy my articles and see it useful to you, you may buy me a coffee, it will help me to keep going and keep creating more content.

๐Ÿ˜ Join our community

Join our community on Discord to get help and support (Node Js 2023 Channel).

๐Ÿ“š Bonus Content ๐Ÿ“š

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

Packages & Libraries

React Js Packages

Courses (Articles)

Top comments (0)