• Register

In the realm of JavaScript, developers often spend a lot of time deciding the correct data structure to use. This is because choosing the correct data structure can make it easier to manipulate that data later, saving time and making your code easier to understand. The two predominant data structures for storing data sets are Object and Array(a type of object). Developers use Object to store key-value pairs and Array to store indexed lists. However, to give developers more flexibility, two new types of iterable objects were introduced in the ECMAScript 2015 specification: Map, which is ordered groups of key-value pairs, and Sets, which are groups of unique values.

In this article, you'll go over Map and Set objects, see what makes them similar to or different from Objects and Array, the properties and methods available to them, and examples of some practical uses.

Map:

A Map is a group of key-value pairs in which any type of data can be used as a key and which can maintain the order of its entries. Maps include both Object (a unique group of key-value pairs) and Array (an ordered group) elements, but conceptually they are more similar to Objects. This is because, while the size and order of the inputs are maintained as in an Array, the inputs themselves are key-value pairs like Objects.

Maps can be initialized with the syntax new Map():

const map = new Map()

 

This gives us an empty Map:

 
Output
Map(0) {}

 

Add values ​​to a Map:

You can add values ​​to a map with the method set(). The first argument will represent the key and the second the value.

Next, three key-value pairs are added to map:

map.set('firstName', 'Luke')
map.set('lastName', 'Skywalker')
map.set('occupation', 'Jedi Knight')

Here, we begin to see how both Object and Array elements are found in Maps. As in the case of an Array, we have a group with index zero and we can also see the number of elements available by default in the Map. In Maps, the syntax is used =>to indicate the key-value pairs such as key => value:

 
Output
Map(3) 0: {"firstName" => "Luke"} 1: {"lastName" => "Skywalker"} 2: {"occupation" => "Jedi Knight"}

 

This example looks like a normal object with string-based keys, but with Maps, we can use any data type as the key.

In addition to setting the values ​​manually in a Map, we can also initialize it with these already included. This is done using an Array of Array, with two elements that are each key-value pairs, which looks like this:

[ [ 'key1', 'value1'], ['key2', 'value2'] ]

Using the following syntax, we can recreate the same Map:

const map = new Map([
  ['firstName', 'Luke'],
  ['lastName', 'Skywalker'],
  ['occupation', 'Jedi Knight'],
])
37,120 points
11 5 4