Set and Map, do you know them both?

Posted June 15, 2021 by Jian Yang (宋金阳)


When you think of data types in Javascript, I sure you can think of Number, String, Boolean, Object, etc.., Yes the above are two majar data types in javascript. in addition, there are many other built-in objects in javascript. there objects are not commonly used, but they are useless, let's look at them together!


Basic introduction

Set is actually very smilar to array, and is also an ordered reference object. the main difference with an array is the value within a set can't be duplicated, while an Array has no such limitation.

const myArray = [1, 1, 2, 2];

const mySet = new Set(myArray);
console.log(mySet); // output Set(2) {1, 2}

Commonly used API

// get length of set
// add value to the set
// delete value of set
// Iterate Set
for (let items of mySet) {

How to use

Since set has the unique characteristic of internal values, it's perfect for de-duplication.

let myArray = [1, 1, 2, 2];

myArray = Array.from(new Set(myArray));

console.log(myArray); // output [1, 2]

// String de-duplication

let myStr = "Google";

myStr = Array.from(new Set(myStr)).join("");

console.log(myStr); //output: Gogle


A map is very similar to object in that they are both key-value pairs.

the main differences are

  • The values ​​inside the Map are ordered (consistent with the order when inserted);
  • The value type of the map is not limited and can be of any types (includes: function, objects, etc.. )

Commonly used API

let myMap = new Map();

let array = [1, 2];

myMap.set(array, 2);

// get the lenght of map

// add values to map
myMap.set("google", "duckduckgo");

// delete value from map

myMap.delete("google"); // return true if successful, false

// Get the value of a key in Map


// Iterate through the Map

for (let item of myMap) {

console.log(myMap); // output Map(1) {Array(2) => 2}

It is extremely important that the values within a Map are ordered, so if there is a need to ensure that the order of traversal is consistent when traversing Objects, then a Map can be used.