11-ES6++: Map and Set in Javascript
Tags: javascript, es6, esnext
Published: 2022-11-20 06:38:50

---
title: 11-ES6++: Map and Set in Javascript
published: true
description: 
series: es6++
tags: javascript, es6, esnext
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1wvd9jpza4jos1pbcc6s.png
# Use a ratio of 100:42 for best results.
# published_at: 2022-10-25 09:51 +0000
---

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

```js
const map = new Map();

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

console.log(map.get('name')); // Hasan
console.log(map.get('age')); // 41
```

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.

```js
const map = new Map();

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

for (const [key, value] of map) {
  console.log(key, value);
}
```

## Passing an Array to Map

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

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

console.log(map.get('name')); // Hasan
console.log(map.get('age')); // 41
```

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

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

// TypeError: object is not iterable
```

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

```js
const set = new Set();

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

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

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?

```js
const set = new Set();

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

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

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.

```js
const obj = { name: 'Hasan' };

const set = new Set();

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

console.log(set.size); // 1
```

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.

```js
const set = new Set();

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

for (const value of set) {
  console.log(value); // Hasan, Ahmed
}
```

## Receiving array in the Set constructor

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

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

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

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

```js
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]
```

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

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

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

console.log(uniqueValues); // [{ name: 'Hasan' }, { name: 'Ahmed' }, { name: 'Hasan' }]
```

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

```js
const obj = { name: 'Hasan' };

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

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

console.log(uniqueValues); // [{ name: 'Hasan' }, { name: 'Ahmed' }]
```

Works as well with arrays.

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

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

console.log(uniqueValues); // [[1, 2], [3, 4]]
```

Duplicate array values by reference are not removed

```js
// 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]]
```

## 🎨 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](https://www.paypal.com/paypalme/hassanzohdy), it will help me to keep going and keep creating more content.

## 😍 Join our community

Join our community on [Discord](https://discord.gg/pb2vmdfhGf) 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

* [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
* [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
* [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

* [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
* [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
* [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

* [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

* [Node Js 2023 Course: Node With Typescript, The Ultimate Guide](https://dev.to/hassanzohdy/nodejs-course-2023-introduction-to-nodejs-3n4e)
* [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)