DEV Community

dotjavascript
dotjavascript

Posted on • Originally published at dotjavascript.com

Set and Map, do you know them both?

Introduction

When you think of data types in Javascript, I sure you can think of Number, String, Boolean, Object, etc.., Yes the above
are two major 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!


Set

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}
Enter fullscreen mode Exit fullscreen mode

Commonly used API

// get length of set
mySet.size();
// add value to the set
mySet.add(3);
// delete value of set
mySet.delete(3);
// Iterate Set
for (let items of mySet) {
  console.log(items);
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Map

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
myMap.size;

// 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

myMap.get("duckduckgo");

// Iterate through the Map

for (let item of myMap) {
  console.log(item);
}

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

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.

Top comments (0)