Chuyển tới nội dung
Home » Javascript New Map With Values | Introduction To Javascript Map Object

Javascript New Map With Values | Introduction To Javascript Map Object

Use Maps more and Objects less

Javascript


let myMap =


new


Map().set(


'GFG'


, 1).set(


'Geeks'


, 2);


let array = [...myMap.keys()];


console.log(array.length);

Conclusion

In this tutorial, you learned about the relationship between arrays, sets, and maps.

We created, modified, and deleted elements in maps and sets. We compared maps and objects, and lastly, we talked about the benefits of sets over arrays.

Summary: in this tutorial, you will learn about the JavaScript Map object that maps a key to a value.

Use Maps more and Objects less
Use Maps more and Objects less

Approach 1: Using array.from() Method

  • Declare a new map object
  • Display the map content
  • Use the keys() method on Map Object to get the keys of Map.
  • Then use the array.from() method to convert a map object to an array.

Example: This example uses an array.from() method to get the keys of the Map in the array.

JavaScript Map examples

Let’s take some examples of using a Map object.

Create a new Map object

Suppose you have a list of

user

objects as follows:


let john = {name: 'John Doe'}, lily = {name: 'Lily Bush'}, peter = {name: 'Peter Drucker'};

Code language: JavaScript (javascript)

Assuming that you have to create a map of users and roles. In this case, you use the following code:


let userRoles = new Map();

Code language: JavaScript (javascript)

The

userRoles

is an instance of the

Map

object and its type is an object as illustrated in the following example:


console.log(typeof(userRoles)); // object console.log(userRoles instanceof Map); // true

Code language: JavaScript (javascript)

Add elements to a Map

To assign a role to a user, you use the

set()

method:


userRoles.set(john, 'admin');

Code language: JavaScript (javascript)

The

set()

method maps user

john

with the

admin

role. Since the

set()

method is chainable, you can save some typing as shown in this example:


userRoles.set(lily, 'editor') .set(peter, 'subscriber');

Code language: JavaScript (javascript)

Initialize a map with an iterable object

As mentioned earlier, you can pass an iterable object to the

Map()

constructor:


let userRoles = new Map([ [john, 'admin'], [lily, 'editor'], [peter, 'subscriber'] ]);

Code language: JavaScript (javascript)

Get an element from a map by key

If you want to see the roles of

John

, you use the

get()

method:


userRoles.get(john); // admin

Code language: JavaScript (javascript)

If you pass a key that does not exist, the

get()

method will return

undefined

.


let foo = {name: 'Foo'}; userRoles.get(foo); //undefined

Code language: JavaScript (javascript)

Check the existence of an element by key

To check if a key exists in the map, you use the

has()

method.


userRoles.has(foo); // false userRoles.has(lily); // true

Code language: JavaScript (javascript)

Get the number of elements in the map

The

size

property returns the number of entries of the Map object.


console.log(userRoles.size); // 3

Code language: JavaScript (javascript)

Iterate over map keys

To get the keys of a

Map

object, you use the

keys()

method. The

keys()

returns a new iterator object that contains the keys of elements in the map.

The following example displays the username of the users in the

userRoles

map object.


let john = { name: 'John Doe' }, lily = { name: 'Lily Bush' }, peter = { name: 'Peter Drucker' }; let userRoles = new Map([ [john, 'admin'], [lily, 'editor'], [peter, 'subscriber'], ]); for (const user of userRoles.keys()) { console.log(user.name); }

Code language: JavaScript (javascript)

Output:


John Doe Lily Bush Peter Drucker

Iterate over map values

Similarly, you can use the

values()

method to get an iterator object that contains values for all the elements in the map:


let john = { name: 'John Doe' }, lily = { name: 'Lily Bush' }, peter = { name: 'Peter Drucker' }; let userRoles = new Map([ [john, 'admin'], [lily, 'editor'], [peter, 'subscriber'], ]); for (let role of userRoles.values()) { console.log(role); }

Code language: JavaScript (javascript)

Output:


admin editor subscriber

Iterate over map elements

Also, the

entries()

method returns an iterator object that contains an array of

[key,value]

of each element in the

Map

object:


let john = { name: 'John Doe' }, lily = { name: 'Lily Bush' }, peter = { name: 'Peter Drucker' }; let userRoles = new Map([ [john, 'admin'], [lily, 'editor'], [peter, 'subscriber'], ]); for (const role of userRoles.entries()) { console.log(`${role[0].name}: ${role[1]}`); }

Code language: JavaScript (javascript)

To make the iteration more natural, you can use destructuring as follows:


let john = { name: 'John Doe' }, lily = { name: 'Lily Bush' }, peter = { name: 'Peter Drucker' }; let userRoles = new Map([ [john, 'admin'], [lily, 'editor'], [peter, 'subscriber'], ]); for (let [user, role] of userRoles.entries()) { console.log(`${user.name}: ${role}`); }

Code language: JavaScript (javascript)

In addition to

for...of

loop, you can use the

forEach()

method of the map object:


let john = { name: 'John Doe' }, lily = { name: 'Lily Bush' }, peter = { name: 'Peter Drucker' }; let userRoles = new Map([ [john, 'admin'], [lily, 'editor'], [peter, 'subscriber'], ]); userRoles.forEach((role, user) => console.log(`${user.name}: ${role}`));

Code language: JavaScript (javascript)

Convert map keys or values to an array

Sometimes, you want to work with an array instead of an iterable object, in this case, you can use the spread operator.

The following example converts keys for each element into an array of keys:


var keys = [...userRoles.keys()]; console.log(keys);

Code language: JavaScript (javascript)

Output:


[ { name: 'John Doe' }, { name: 'Lily Bush' }, { name: 'Peter Drucker' } ]

Code language: JavaScript (javascript)

The following converts the values of elements to an array:


let roles = [...userRoles.values()]; console.log(roles);

Code language: JavaScript (javascript)

Output


[ 'admin', 'editor', 'subscriber' ]

Code language: JSON / JSON with Comments (json)

Delete an element by key

To delete an entry in the map, you use the

delete()

method.


userRoles.delete(john);

Code language: CSS (css)

Delete all elements in the map

To delete all entries in the

Map

object, you use the

clear()

method:


userRoles.clear();

Code language: CSS (css)

Hence, the size of the map now is zero.


console.log(userRoles.size); // 0

Code language: JavaScript (javascript)

Do you really know how to use a Map in Javascript? 🤔 #javascript  #map #datatypes #tutorial
Do you really know how to use a Map in Javascript? 🤔 #javascript #map #datatypes #tutorial

Map Methods

Method Description
new Map() Creates a new Map object
set() Sets the value for a key in a Map
get() Gets the value for a key in a Map
clear() Removes all the elements from a Map
delete() Removes a Map element specified by a key
has() Returns true if a key exists in a Map
forEach() Invokes a callback for each key/value pair in a Map
entries() Returns an iterator object with the [key, value] pairs in a Map
keys() Returns an iterator object with the keys in a Map
values() Returns an iterator object of the values in a Map
Property Description
size Returns the number of Map elements

Browser compatibility

BCD tables only load in the browser

Pass an array containing arrays of key-value pairs to the

Map()

constructor
to initialize a

Map

with values.

The first element in each array should be the key and the second, the value.


// ✅ Create a Map from an Array const map1 = new Map([ ['name', 'bobby hadz'], ['country', 'Chile'], ]); // 👇️ Map(2) { 'name' => 'bobby hadz', 'country' => 'Chile' } console.log(map1); console.log(map1.get('name')); // 👉️ bobby hadz

We passed a two-dimensional array to the
Map()
constructor to initialize the

Map

with values.

The first element in each nested array is the key and the second is the value.

You can also convert a

Map

to a two-dimensional array.


const arr = Array.from(map1); // 👉️ [['country], 'Chile], ['name', 'Tom'], ['age', 30]] console.log(arr);

We used the Array.from method to convert
a

Map

object to an array.

Alternatively, you can use the

Object.entries()

method.

The

Object.entries()

method returns an array of key-value pairs that can be
used to initialize a

Map

.


const obj = {name: 'bobby hadz', country: 'Chile'}; const map1 = new Map(Object.entries(obj)); // 👇️ Map(2) { 'name' => 'bobby hadz', 'country' => 'Chile' } console.log(map1);

The Object.entries method returns a two-dimensional array, where each nested array contains a key and a value.


const obj = {name: 'bobby hadz', country: 'Chile'}; // 👇️ [ [ 'name', 'bobby hadz' ], [ 'country', 'Chile' ] ] console.log(Object.entries(obj));

The

Map

constructor expects an array of key-value pairs as a parameter, so the

Object.entries()

method does exactly what we need.

An alternative approach is to create an empty

Map

and manually set its
key-value pairs.


const map1 = new Map(); map1.set('name', 'bobby hadz'); map1.set('country', 'Chile'); map1.set('age', 30); // Map(3) { 'name' => 'bobby hadz', 'country' => 'Chile', 'age' => 30 } console.log(map1); console.log(map1.get('name')); // 👉️ bobby hadz

We used the
Map()
constructor to create an empty

Map

object.

The Map.set method takes a key and
a value as parameters and adds the key-value pair to the

Map

object.

The

Map.set

method returns the

Map

object, so you can chain calls to the
method.


const map1 = new Map(); map1 .set('name', 'bobby hadz') .set('country', 'Chile') .set('age', 30) .set('salary', 50); // Map(4) { // 'name' => 'bobby hadz', // 'country' => 'Chile', // 'age' => 30, // 'salary' => 50 // } console.log(map1);

On each call to the

Map.set()

method, the

Map

object gets returned, so we
can call the

set()

method again.

If you set the value of the same key multiple times, the last value wins.


const map1 = new Map(); map1.set('name', 'alice'); map1.set('name', 'bobby'); console.log(map1); // 👉️ Map(1) { 'name' => 'bobby' } console.log(map1.get('name')); // 👉️ bobby

The Map.get method takes a key as a parameter and returns the corresponding value.

You can also initialize a Map with values from another Map.


const map1 = new Map(); map1.set('name', 'bobby hadz'); map1.set('country', 'Chile'); map1.set('age', 30); const map2 = new Map(map1); // 👇️ Map(3) { 'name' => 'bobby hadz', 'country' => 'Chile', 'age' => 30 } console.log(map2); console.log(map2.get('name')); // 👉️ bobby hadz console.log(map2.get('country')); // 👉️ Chile

We created a

Map

object, added 3 key-value pairs to it and used it to
initialize a new

Map

object.

You can directly pass one

Map

object to the

Map()

constructor to create
another

Map

object.

You can learn more about the related topics by checking out the following tutorials:

How to Initialize a Map with Values in JavaScript

Maps in Javascript (Map Object)
Maps in Javascript (Map Object)

Conclusion

The “set()” method, the “Object.entries()” method or the “Array” approach can be applied to initialize a map with values in JavaScript. The set() method can be utilized to simply set the values via the created object, whereas the Object.entries() method and the array approach can be implemented to create a map from the object and array, respectively. This tutorial explained how to initialize/create a map with values in JavaScript.

There are three major iterables available in JavaScript: Arrays, Maps, and Sets.

In this article, we will cover the following topics:

  • What is an Array?
  • What is a Set?
  • What is a Map?
  • How to Create a Seta. How to Create a Set with a Value
  • Properties and Methods of a Seta. How to use the

    add

    method in a setb. How to use the

    has

    method in a setc. How to use the

    delete

    method in a setd. How to use the

    clear

    method in a sete. How to use the

    entries

    method in a setf. How to use the

    values

    method in a setg. How to use the

    size

    property in a seth. How to use

    forEach

    in a seti. How to use a set to Get Unique Value from an Array.
  • How to Create a Map
  • Properties and Methods of Mapa. How to Get Values from the Map Objectb. How to Add Data with the

    set

    Methodc. How to Search an Element with the

    has

    Methodd. How to Delete an Element with the

    delete

    Methode. How to Clear All Elements with the

    clear

    Methodf. How to get all Entries in a Map with the

    entries

    Methodg. How to Get All Keys in a Map with the

    keys

    Methodh. How to Get All Values in a Map with the

    values

    Methodi. How to Enumerate Over a Mapj. How to Use Size Property in Map
  • Map vs Object – What’s the Difference?
  • Benefits of Sets over Arrays
  • Conclusion

What is a Set?

A set is a data structure used for storing data of any length and kind. Sets are iterables that have various special methods that are different from arrays.

Some of the characteristics of sets are that the order of elements is not guaranteed, you can’t access elements by index, and you can’t have duplicate elements. Sets are a great choice when you want to store data without duplicates.

New Map Javascript Example Tutorial - What Is the Difference?
New Map Javascript Example Tutorial – What Is the Difference?

Introduction to JavaScript Map object

Before ES6, we often used an object to emulate a map by mapping a key to a value of any type. But using an object as a map has some side effects:

  1. An object always has a default key like the prototype.
  2. A key of an object must be a string or a symbol, you cannot use an object as a key.
  3. An object does not have a property that represents the size of the map.

ES6 provides a new collection type called

Map

that addresses these deficiencies.

By definition, a

Map

object holds key-value pairs. Keys are unique in a Map’s collection. In other words, a key in a Map object only appears once.

Keys and values of a Map can be any values.

When iterating a

Map

object, each iteration returns a 2-member array of

[key, value]

. The iteration order follows the insertion order which corresponds to the order in which each key-value pair was first inserted into the Map by the

set()

method.

To create a new

Map

, you use the following syntax:


let map = new Map([iterable]);

Code language: JavaScript (javascript)

The

Map()

accepts an optional iterable object whose elements are key-value pairs.

Summary


Map

– is a collection of keyed values.

Methods and properties:


  • new Map([iterable])

    – creates the map, with optional

    iterable

    (e.g. array) of

    [key,value]

    pairs for initialization.

  • map.set(key, value)

    – stores the value by the key, returns the map itself.

  • 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 element by the key, returns

    true

    if

    key

    existed at the moment of the call, otherwise

    false

    .

  • map.clear()

    – removes everything from the map.

  • map.size

    – returns the current element count.

The differences from a regular

Object

:

  • Any keys, objects can be keys.
  • Additional convenient methods, the

    size

    property.


Set

– is a collection of unique values.

Methods and properties:


  • new Set([iterable])

    – creates the set, with optional

    iterable

    (e.g. array) of values for initialization.

  • set.add(value)

    – adds a value (does nothing if

    value

    exists), returns the set itself.

  • set.delete(value)

    – removes the value, returns

    true

    if

    value

    existed at the moment of the call, otherwise

    false

    .

  • set.has(value)

    – returns

    true

    if the value exists in the set, otherwise

    false

    .

  • set.clear()

    – removes everything from the set.

  • set.size

    – is the elements count.

Iteration over

Map

and

Set

is always in the insertion order, so we can’t say that these collections are unordered, but we can’t reorder elements or directly get an element by its number.

This write-up will discuss the approaches to initializing a map with values in JavaScript.

JavaScript Map and Set Explained
JavaScript Map and Set Explained

Instance methods


Map.prototype.clear()

Removes all key-value pairs from the


Map

object.


Map.prototype.delete()

Returns


true

if an element in the

Map

object existed and has been removed, or

false

if the element does not exist.

map.has(key)

will return

false

afterwards.


Map.prototype.entries()

Returns a new Iterator object that contains a two-member array of


[key, value]

for each element in the

Map

object in insertion order.


Map.prototype.forEach()

Calls


callbackFn

once for each key-value pair present in the

Map

object, in insertion order. If a

thisArg

parameter is provided to

forEach

, it will be used as the

this

value for each callback.


Map.prototype.get()

Returns the value associated to the passed key, or


undefined

if there is none.


Map.prototype.has()

Returns a boolean indicating whether a value has been associated with the passed key in the


Map

object or not.


Map.prototype.keys()

Returns a new Iterator object that contains the keys for each element in the


Map

object in insertion order.


Map.prototype.set()

Sets the value for the passed key in the


Map

object. Returns the

Map

object.


Map.prototype.values()

Returns a new Iterator object that contains the values for each element in the


Map

object in insertion order.


Map.prototype[@@iterator]()

Returns a new Iterator object that contains a two-member array of


[key, value]

for each element in the

Map

object in insertion order.

Javascript


let myMap =


new


Map().set(


'GFG'


, 1).set(


'Geeks'


, 2);


let array = Array.from(myMap.keys());


console.log(array.length);

  • Declare a new map object
  • Display the map content
  • Use the [ …myMap.keys() ] method on Map Object to get the keys of Map as an array.

Example: This example uses the [ …Map.keys() ] method to get the keys of the Map in the array.

JavaScript map() method in 7 minutes! 🗺
JavaScript map() method in 7 minutes! 🗺

Maps

A Map is a collection of key/value pairs that can use any data type as a key and can maintain the order of its entries. Maps have elements of both Objects (a unique key/value pair collection) and Arrays (an ordered collection), but are more similar to Objects conceptually. This is because, although the size and order of entries is preserved like an Array, the entries themselves are key/value pairs like Objects.

Maps can be initialized with the

new Map()

syntax:


const map = new Map()

This gives us an empty Map:


Map(0) {}

Adding Values to a Map

You can add values to a map with the

set()

method. The first argument will be the key, and the second argument will be the value.

The following adds three key/value pairs to

map

:


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

Here we begin to see how Maps have elements of both Objects and Arrays. Like an Array, we have a zero-indexed collection, and we can also see how many items are in the Map by default. Maps use the

=>

syntax to signify key/value pairs as

key => value

:


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

This example looks similar to a regular object with string-based keys, but we can use any data type as a key with Map.

In addition to manually setting values on a Map, we can also initialize a Map with values already. We do this using an Array of Arrays containing 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'], ])

Incidentally, this syntax is the same as the result of calling

Object.entries()

on an Object. This provides a ready-made way to convert an Object to a Map, as shown in the following code block:


const luke = { firstName: 'Luke', lastName: 'Skywalker', occupation: 'Jedi Knight', } const map = new Map(Object.entries(luke))

Alternatively, you can turn a Map back into an Object or an Array with a single line of code.

The following converts a Map to an Object:


const obj = Object.fromEntries(map)

This will result in the following value of

obj

:


{firstName: "Luke", lastName: "Skywalker", occupation: "Jedi Knight"}

Now, let’s convert a Map to an Array:


const arr = Array.from(map)

This will result in the following Array for

arr

:


[ ['firstName', 'Luke'], ['lastName', 'Skywalker'], ['occupation', 'Jedi Knight'] ]

Map Keys

Maps accept any data type as a key, and do not allow duplicate key values. We can demonstrate this by creating a map and using non-string values as keys, as well as setting two values to the same key.

First, let’s initialize a map with non-string keys:


const map = new Map() map.set('1', 'String one') map.set(1, 'This will be overwritten') map.set(1, 'Number one') map.set(true, 'A Boolean')

This example will override the first key of with the subsequent one, and it will treat

'1'

the string and the number as unique keys:


0: {"1" => "String one"} 1: {1 => "Number one"} 2: {true => "A Boolean"}

Although it is a common belief that a regular JavaScript Object can already handle Numbers, booleans, and other primitive data types as keys, this is actually not the case, because Objects change all keys to strings.

As an example, initialize an object with a numerical key and compare the value for a numerical key and a stringified

"1"

key:


// Initialize an object with a numerical key const obj = { 1: 'One' } // The key is actually a string obj[1] === obj['1'] // true

This is why if you attempt to use an Object as a key, it will print out the string

object Object

instead.

As an example, create an Object and then use it as the key of another Object:


// Create an object const objAsKey = { foo: 'bar' } // Use this object as the key of another object const obj = { [objAsKey]: 'What will happen?', }

This will yield the following:


{[object Object]: "What will happen?"}

This is not the case with Map. Try creating an Object and setting it as the key of a Map:


// Create an object const objAsKey = { foo: 'bar' } const map = new Map() // Set this object as the key of a Map map.set(objAsKey, 'What will happen?')

The

key

of the Map element is now the object we created.


key: {foo: "bar"} value: "What will happen?"

There is one important thing to note about using an Object or Array as a key: the Map is using the reference to the Object to compare equality, not the literal value of the Object. In JavaScript

{} === {}

returns

false

, because the two Objects are not the same two Objects, despite having the same (empty) value.

That means that adding two unique Objects with the same value will create a Map with two entries:


// Add two unique but similar objects as keys to a Map map.set({}, 'One') map.set({}, 'Two')

This will yield the following:


Map(2) {{…} => "One", {…} => "Two"}

But using the same Object reference twice will create a Map with one entry.


// Add the same exact object twice as keys to a Map const obj = {} map.set(obj, 'One') map.set(obj, 'Two')

Which will result in the following:


Map(1) {{…} => "Two"}

The second

set()

is updating the same exact key as the first, so we end up with a Map that only has one value.

Getting and Deleting Items from a Map

One of the disadvantages of working with Objects is that it can be difficult to enumerate them, or work with all the keys or values. The Map structure, by contrast, has a lot of built-in properties that make working with their elements more direct.

We can initialize a new Map to demonstrate the following methods and properties:

delete()

,

has()

,

get()

, and

size

.


// Initialize a new Map const map = new Map([ ['animal', 'otter'], ['shape', 'triangle'], ['city', 'New York'], ['country', 'Bulgaria'], ])

Use the

has()

method to check for the existence of an item in a map.

has()

will return a Boolean.


// Check if a key exists in a Map map.has('shark') // false map.has('country') // true

Use the

get()

method to retrieve a value by key.


// Get an item from a Map map.get('animal') // "otter"

One particular benefit Maps have over Objects is that you can find the size of the Map at any time, like you can with an Array. You can get the count of items in a Map with the

size

property. This involves fewer steps than converting an Object to an Array to find the length.


// Get the count of items in a Map map.size // 4

Use the

delete()

method to remove an item from a Map by key. The method will return a Boolean—

true

if an item existed and was deleted, and

false

if it did not match any item.


// Delete an item from a Map by key map.delete('city') // true

This will result in the following Map:


Map(3) {"animal" => "otter", "shape" => "triangle", "country" => "Bulgaria"}

Finally, a Map can be cleared of all values with

map.clear()

.


// Empty a Map map.clear()

This will yield:


Map(0) {}

Keys, Values, and Entries for Maps

Objects can retrieve keys, values, and entries by using the properties of the

Object

constructor. Maps, on the other hand, have prototype methods that allow us to get the keys, values, and entries of the Map instance directly.

The

keys()

,

values()

, and

entries()

methods all return a

MapIterator

, which is similar to an Array in that you can use

for...of

to loop through the values.

Here is another example of a Map, which we can use to demonstrate these methods.


const map = new Map([ [1970, 'bell bottoms'], [1980, 'leg warmers'], [1990, 'flannel'], ])

The

keys()

method returns the keys:


map.keys()


MapIterator {1970, 1980, 1990}

The

values()

method returns the values:


map.values()


MapIterator {"bell bottoms", "leg warmers", "flannel"}

The

entries()

method returns an array of key/value pairs:


map.entries()


MapIterator {1970 => "bell bottoms", 1980 => "leg warmers", 1990 => "flannel"}

Iteration with Map

Map has a built-in

forEach

method, similar to an Array, for built-in iteration. However, there is a bit of a difference in what they iterate over. The callback of a Map’s

forEach

iterates through the

value

,

key

, and

map

itself, while the Array version iterates through the

item

,

index

, and

array

itself.


// Map Map.prototype.forEach((value, key, map) = () => {} // Array Array.prototype.forEach((item, index, array) = () => {}

This is a big advantage for Maps over Objects, as Objects need to be converted with

keys()

,

values()

, or

entries()

, and there is not an simple way to retrieve the properties of an Object without converting it.

To demonstrate this, let’s iterate through our Map and log the key/value pairs to the console:


// Log the keys and values of the Map with forEach map.forEach((value, key) => { console.log(`${key}: ${value}`) })

This will give:


1970: bell bottoms 1980: leg warmers 1990: flannel

Since a

for...of

loop iterates over iterables like Map and Array, we can get the exact same result by destructuring the array of Map items:


// Destructure the key and value out of the Map item for (const [key, value] of map) { // Log the keys and values of the Map with for...of console.log(`${key}: ${value}`) }

Map Properties and Methods

The following table shows a list of Map properties and methods for quick reference:

Properties/Methods Description Returns
Appends a key/value pair to a Map
Removes a key/value pair from a Map by key Boolean
Returns a value by key value
Checks for the presence of an element in a Map by key Boolean
Removes all items from a Map N/A
Returns all keys in a Map
Returns all values in a Map
Returns all keys and values in a Map as
Iterates through the Map in insertion order N/A
Returns the number of items in a Map Number

When to Use Map

Summing up, Maps are similar to Objects in that they hold key/value pairs, but Maps have several advantages over objects:

  • Size – Maps have a

    size

    property, whereas Objects do not have a built-in way to retrieve their size.
  • Iteration – Maps are directly iterable, whereas Objects are not.
  • Flexibility – Maps can have any data type (primitive or Object) as the key to a value, while Objects can only have strings.
  • Ordered – Maps retain their insertion order, whereas objects do not have a guaranteed order.

Due to these factors, Maps are a powerful data structure to consider. However, Objects haves some important advantages as well:

  • JSON – Objects work flawlessly with

    JSON.parse()

    and

    JSON.stringify()

    , two essential functions for working with JSON, a common data format that many REST APIs deal with.
  • Working with a single element – Working with a known value in an Object, you can access it directly with the key without the need to use a method, such as Map’s

    get()

    .

This list will help you decide if a Map or Object is the right data structure for your use case.

Approach 2: Initialize a Map With Values in JavaScript Using Object.entries() Method

The “Object.entries()” method gives an object array in the form of enumerable [key, value] pairs. This method can be utilized to initialize a map from the created object.

Syntax

In the above syntax:

“ob” refers to the object whose values in the form of “key-value” pairs need to be returned.

Example

Let’s go through the below-stated demo:

Perform the following steps, as given in the above code:

  • Create an “object” having the stated properties and their respective values.
  • In the next step, likewise, create a new map named “initMap”.
  • Also, apply the “Object.entries()” method to return the object values from the created object in the form of “key-value” pairs and add them to the map.
  • Finally, display the map created from the object on the console.

Output

Here, it can be seen that the object values are transformed into the map successfully.

Lecture 8 : OOPS in Python | Object Oriented Programming | Classes & Objects | Python Full Course
Lecture 8 : OOPS in Python | Object Oriented Programming | Classes & Objects | Python Full Course

Set

A

Set

is a special type collection – “set of values” (without keys), where each value may occur only once.

Its main methods are:


  • new Set([iterable])

    – creates the set, and if an

    iterable

    object is provided (usually an array), copies values from it into the set.

  • set.add(value)

    – adds a value, returns the set itself.

  • set.delete(value)

    – removes the value, returns

    true

    if

    value

    existed at the moment of the call, otherwise

    false

    .

  • set.has(value)

    – returns

    true

    if the value exists in the set, otherwise

    false

    .

  • set.clear()

    – removes everything from the set.

  • set.size

    – is the elements count.

The main feature is that repeated calls of

set.add(value)

with the same value don’t do anything. That’s the reason why each value appears in a

Set

only once.

For example, we have visitors coming, and we’d like to remember everyone. But repeated visits should not lead to duplicates. A visitor must be “counted” only once.


Set

is just the right thing for that:


let set = new Set(); let john = { name: "John" }; let pete = { name: "Pete" }; let mary = { name: "Mary" }; // visits, some users come multiple times set.add(john); set.add(pete); set.add(mary); set.add(john); set.add(mary); // set keeps only unique values alert( set.size ); // 3 for (let user of set) { alert(user.name); // John (then Pete and Mary) }

The alternative to

Set

could be an array of users, and the code to check for duplicates on every insertion using arr.find. But the performance would be much worse, because this method walks through the whole array checking every element.

Set

is much better optimized internally for uniqueness checks.

Javascript


let myMap =


new


Map().set(


'GFG'


, 1)


.set(


'Geeks'


, 2)


.set(


'Geeksforgeeks'


, 3);


let arr = [];


myMap.forEach((values, keys) => {


arr.push(keys);


});


console.log(arr);

Output

[ ‘GFG’, ‘Geeks’, ‘Geeksforgeeks’ ]

In this approach, we are using Lodash _.toArray() method that accept any value and convert it into an array.

Example: This example shows the implementation of the above-explained approach.

The easiest way to setup google maps in next.js
The easiest way to setup google maps in next.js

Maps

A Map is a collection of key/value pairs that can use any data type as a key and can maintain the order of its entries. Maps have elements of both Objects (a unique key/value pair collection) and Arrays (an ordered collection), but are more similar to Objects conceptually. This is because, although the size and order of entries is preserved like an Array, the entries themselves are key/value pairs like Objects.

Maps can be initialized with the

new Map()

syntax:


const map = new Map()

This gives us an empty Map:


Map(0) {}

Adding Values to a Map

You can add values to a map with the

set()

method. The first argument will be the key, and the second argument will be the value.

The following adds three key/value pairs to

map

:


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

Here we begin to see how Maps have elements of both Objects and Arrays. Like an Array, we have a zero-indexed collection, and we can also see how many items are in the Map by default. Maps use the

=>

syntax to signify key/value pairs as

key => value

:


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

This example looks similar to a regular object with string-based keys, but we can use any data type as a key with Map.

In addition to manually setting values on a Map, we can also initialize a Map with values already. We do this using an Array of Arrays containing 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'], ])

Incidentally, this syntax is the same as the result of calling

Object.entries()

on an Object. This provides a ready-made way to convert an Object to a Map, as shown in the following code block:


const luke = { firstName: 'Luke', lastName: 'Skywalker', occupation: 'Jedi Knight', } const map = new Map(Object.entries(luke))

Alternatively, you can turn a Map back into an Object or an Array with a single line of code.

The following converts a Map to an Object:


const obj = Object.fromEntries(map)

This will result in the following value of

obj

:


{firstName: "Luke", lastName: "Skywalker", occupation: "Jedi Knight"}

Now, let’s convert a Map to an Array:


const arr = Array.from(map)

This will result in the following Array for

arr

:


[ ['firstName', 'Luke'], ['lastName', 'Skywalker'], ['occupation', 'Jedi Knight'] ]

Map Keys

Maps accept any data type as a key, and do not allow duplicate key values. We can demonstrate this by creating a map and using non-string values as keys, as well as setting two values to the same key.

First, let’s initialize a map with non-string keys:


const map = new Map() map.set('1', 'String one') map.set(1, 'This will be overwritten') map.set(1, 'Number one') map.set(true, 'A Boolean')

This example will override the first key of with the subsequent one, and it will treat

'1'

the string and the number as unique keys:


0: {"1" => "String one"} 1: {1 => "Number one"} 2: {true => "A Boolean"}

Although it is a common belief that a regular JavaScript Object can already handle Numbers, booleans, and other primitive data types as keys, this is actually not the case, because Objects change all keys to strings.

As an example, initialize an object with a numerical key and compare the value for a numerical key and a stringified

"1"

key:


// Initialize an object with a numerical key const obj = { 1: 'One' } // The key is actually a string obj[1] === obj['1'] // true

This is why if you attempt to use an Object as a key, it will print out the string

object Object

instead.

As an example, create an Object and then use it as the key of another Object:


// Create an object const objAsKey = { foo: 'bar' } // Use this object as the key of another object const obj = { [objAsKey]: 'What will happen?', }

This will yield the following:


{[object Object]: "What will happen?"}

This is not the case with Map. Try creating an Object and setting it as the key of a Map:


// Create an object const objAsKey = { foo: 'bar' } const map = new Map() // Set this object as the key of a Map map.set(objAsKey, 'What will happen?')

The

key

of the Map element is now the object we created.


key: {foo: "bar"} value: "What will happen?"

There is one important thing to note about using an Object or Array as a key: the Map is using the reference to the Object to compare equality, not the literal value of the Object. In JavaScript

{} === {}

returns

false

, because the two Objects are not the same two Objects, despite having the same (empty) value.

That means that adding two unique Objects with the same value will create a Map with two entries:


// Add two unique but similar objects as keys to a Map map.set({}, 'One') map.set({}, 'Two')

This will yield the following:


Map(2) {{…} => "One", {…} => "Two"}

But using the same Object reference twice will create a Map with one entry.


// Add the same exact object twice as keys to a Map const obj = {} map.set(obj, 'One') map.set(obj, 'Two')

Which will result in the following:


Map(1) {{…} => "Two"}

The second

set()

is updating the same exact key as the first, so we end up with a Map that only has one value.

Getting and Deleting Items from a Map

One of the disadvantages of working with Objects is that it can be difficult to enumerate them, or work with all the keys or values. The Map structure, by contrast, has a lot of built-in properties that make working with their elements more direct.

We can initialize a new Map to demonstrate the following methods and properties:

delete()

,

has()

,

get()

, and

size

.


// Initialize a new Map const map = new Map([ ['animal', 'otter'], ['shape', 'triangle'], ['city', 'New York'], ['country', 'Bulgaria'], ])

Use the

has()

method to check for the existence of an item in a map.

has()

will return a Boolean.


// Check if a key exists in a Map map.has('shark') // false map.has('country') // true

Use the

get()

method to retrieve a value by key.


// Get an item from a Map map.get('animal') // "otter"

One particular benefit Maps have over Objects is that you can find the size of the Map at any time, like you can with an Array. You can get the count of items in a Map with the

size

property. This involves fewer steps than converting an Object to an Array to find the length.


// Get the count of items in a Map map.size // 4

Use the

delete()

method to remove an item from a Map by key. The method will return a Boolean—

true

if an item existed and was deleted, and

false

if it did not match any item.


// Delete an item from a Map by key map.delete('city') // true

This will result in the following Map:


Map(3) {"animal" => "otter", "shape" => "triangle", "country" => "Bulgaria"}

Finally, a Map can be cleared of all values with

map.clear()

.


// Empty a Map map.clear()

This will yield:


Map(0) {}

Keys, Values, and Entries for Maps

Objects can retrieve keys, values, and entries by using the properties of the

Object

constructor. Maps, on the other hand, have prototype methods that allow us to get the keys, values, and entries of the Map instance directly.

The

keys()

,

values()

, and

entries()

methods all return a

MapIterator

, which is similar to an Array in that you can use

for...of

to loop through the values.

Here is another example of a Map, which we can use to demonstrate these methods.


const map = new Map([ [1970, 'bell bottoms'], [1980, 'leg warmers'], [1990, 'flannel'], ])

The

keys()

method returns the keys:


map.keys()


MapIterator {1970, 1980, 1990}

The

values()

method returns the values:


map.values()


MapIterator {"bell bottoms", "leg warmers", "flannel"}

The

entries()

method returns an array of key/value pairs:


map.entries()


MapIterator {1970 => "bell bottoms", 1980 => "leg warmers", 1990 => "flannel"}

Iteration with Map

Map has a built-in

forEach

method, similar to an Array, for built-in iteration. However, there is a bit of a difference in what they iterate over. The callback of a Map’s

forEach

iterates through the

value

,

key

, and

map

itself, while the Array version iterates through the

item

,

index

, and

array

itself.


// Map Map.prototype.forEach((value, key, map) = () => {} // Array Array.prototype.forEach((item, index, array) = () => {}

This is a big advantage for Maps over Objects, as Objects need to be converted with

keys()

,

values()

, or

entries()

, and there is not an simple way to retrieve the properties of an Object without converting it.

To demonstrate this, let’s iterate through our Map and log the key/value pairs to the console:


// Log the keys and values of the Map with forEach map.forEach((value, key) => { console.log(`${key}: ${value}`) })

This will give:


1970: bell bottoms 1980: leg warmers 1990: flannel

Since a

for...of

loop iterates over iterables like Map and Array, we can get the exact same result by destructuring the array of Map items:


// Destructure the key and value out of the Map item for (const [key, value] of map) { // Log the keys and values of the Map with for...of console.log(`${key}: ${value}`) }

Map Properties and Methods

The following table shows a list of Map properties and methods for quick reference:

Properties/Methods Description Returns
Appends a key/value pair to a Map
Removes a key/value pair from a Map by key Boolean
Returns a value by key value
Checks for the presence of an element in a Map by key Boolean
Removes all items from a Map N/A
Returns all keys in a Map
Returns all values in a Map
Returns all keys and values in a Map as
Iterates through the Map in insertion order N/A
Returns the number of items in a Map Number

When to Use Map

Summing up, Maps are similar to Objects in that they hold key/value pairs, but Maps have several advantages over objects:

  • Size – Maps have a

    size

    property, whereas Objects do not have a built-in way to retrieve their size.
  • Iteration – Maps are directly iterable, whereas Objects are not.
  • Flexibility – Maps can have any data type (primitive or Object) as the key to a value, while Objects can only have strings.
  • Ordered – Maps retain their insertion order, whereas objects do not have a guaranteed order.

Due to these factors, Maps are a powerful data structure to consider. However, Objects haves some important advantages as well:

  • JSON – Objects work flawlessly with

    JSON.parse()

    and

    JSON.stringify()

    , two essential functions for working with JSON, a common data format that many REST APIs deal with.
  • Working with a single element – Working with a known value in an Object, you can access it directly with the key without the need to use a method, such as Map’s

    get()

    .

This list will help you decide if a Map or Object is the right data structure for your use case.

Object.entries: Map from Object

When a

Map

is created, we can pass an array (or another iterable) with key/value pairs for initialization, like this:

If we have a plain object, and we’d like to create a

Map

from it, then we can use built-in method Object.entries(obj) that returns an array of key/value pairs for an object exactly in that format.

So we can create a map from an object like this:

Here,

Object.entries

returns the array of key/value pairs:

[ ["name","John"], ["age", 30] ]

. That’s what

Map

needs.

How to load Maps JavaScript API in React (2023)
How to load Maps JavaScript API in React (2023)

Iteration over Set

We can loop over a set either with

for..of

or using

forEach

:

Note the funny thing. The callback function passed in

forEach

has 3 arguments: a

value

, then the same value

valueAgain

, and then the target object. Indeed, the same value appears in the arguments twice.

That’s for compatibility with

Map

where the callback passed

forEach

has three arguments. Looks a bit strange, for sure. But this may help to replace

Map

with

Set

in certain cases with ease, and vice versa.

The same methods

Map

has for iterators are also supported:


  • set.keys()

    – returns an iterable object for values,

  • set.values()

    – same as

    set.keys()

    , for compatibility with

    Map

    ,

  • set.entries()

    – returns an iterable object for entries

    [value, value]

    , exists for compatibility with

    Map

    .

Create a Map from an Array

An easy way to initialize a map with values is by creating a new map and pass it an array as the parameter.

When you pass in an array of key-value pairs, the map will automatically create a new key-value pair for each item in the array.

Let’s look at an example of this:


const values = [ ["name", "John"], ["age", 30] ];

Now we can use this to create a new map with the values:


const values = [ ["name", "John"], ["age", 30] ]; const map = new Map(values); console.log(map);


Map(2) {'name' => 'John', 'age' => 30}

JavaScript Array Map Method Practice in 5 Minutes
JavaScript Array Map Method Practice in 5 Minutes

Browser compatibility

BCD tables only load in the browser

How to convert Map keys to an array in JavaScript ?

In this article, we are given a Map and the task is to get the keys of the map into an array using JavaScript. We can access the keys by using the Map keys() method.

We have a few methods to do this that are described below:

Iteration over Map

For looping over a

map

, there are 3 methods:


  • map.keys()

    – returns an iterable for keys,

  • map.values()

    – returns an iterable for values,

  • map.entries()

    – returns an iterable for entries

    [key, value]

    , it’s used by default in

    for..of

    .

For instance:


let recipeMap = new Map([ ['cucumber', 500], ['tomatoes', 350], ['onion', 50] ]); // iterate over keys (vegetables) for (let vegetable of recipeMap.keys()) { alert(vegetable); // cucumber, tomatoes, onion } // iterate over values (amounts) for (let amount of recipeMap.values()) { alert(amount); // 500, 350, 50 } // iterate over [key, value] entries for (let entry of recipeMap) { // the same as of recipeMap.entries() alert(entry); // cucumber,500 (and so on) }

The iteration goes in the same order as the values were inserted.

Map

preserves this order, unlike a regular

Object

.

Besides that,

Map

has a built-in

forEach

method, similar to

Array

:


// runs the function for each (key, value) pair recipeMap.forEach( (value, key, map) => { alert(`${key}: ${value}`); // cucumber: 500 etc });

Map data structure & ES6 map object - Beau teaches JavaScript
Map data structure & ES6 map object – Beau teaches JavaScript

Set

A Set is a collection of unique values. Unlike a Map, a Set is conceptually more similar to an Array than an Object, since it is a list of values and not key/value pairs. However, Set is not a replacement for Arrays, but rather a supplement for providing additional support for working with duplicated data.

You can initialize Sets with the

new Set()

syntax.


const set = new Set()

This gives us an empty Set:


Set(0) {}

Items can be added to a Set with the

add()

method. (This is not to be confused with the

set()

method available to Map, although they are similar.)


// Add items to a Set set.add('Beethoven') set.add('Mozart') set.add('Chopin')

Since Sets can only contain unique values, any attempt to add a value that already exists will be ignored.


set.add('Chopin') // Set will still contain 3 unique values

Note: The same equality comparison that applies to Map keys applies to Set items. Two objects that have the same value but do not share the same reference will not be considered equal.

You can also initialize Sets with an Array of values. If there are duplicate values in the array, they will be removed from the Set.


// Initialize a Set from an Array const set = new Set(['Beethoven', 'Mozart', 'Chopin', 'Chopin'])


Set(3) {"Beethoven", "Mozart", "Chopin"}

Conversely, a Set can be converted into an Array with one line of code:


const arr = [...set]


(3) ["Beethoven", "Mozart", "Chopin"]

Set has many of the same methods and properties as Map, including

delete()

,

has()

,

clear()

, and

size

.


// Delete an item set.delete('Beethoven') // true // Check for the existence of an item set.has('Beethoven') // false // Clear a Set set.clear() // Check the size of a Set set.size // 0

Note that Set does not have a way to access a value by a key or index, like

Map.get(key)

or

arr[index]

.

Keys, Values, and Entries for Sets

Map and Set both have

keys()

,

values()

, and

entries()

methods that return an Iterator. However, while each one of these methods have a distinct purpose in Map, Sets do not have keys, and therefore keys are an alias for values. This means that

keys()

and

values()

will both return the same Iterator, and

entries()

will return the value twice. It makes the most sense to only use

values()

with Set, as the other two methods exist for consistency and cross-compatibility with Map.


const set = new Set([1, 2, 3]) // Get the values of a set set.values()


SetIterator {1, 2, 3}

Iteration with Set

Like Map, Set has a built-in

forEach()

method. Since Sets don’t have keys, the first and second parameter of the

forEach()

callback return the same value, so there is no use case for it outside of compatibility with Map. The parameters of

forEach()

are

(value, key, set)

.

Both

forEach()

and

for...of

can be used on Set. First, let’s look at

forEach()

iteration:


const set = new Set(['hi', 'hello', 'good day']) // Iterate a Set with forEach set.forEach((value) => console.log(value))

Then we can write the

for...of

version:


// Iterate a Set with for...of for (const value of set) { console.log(value) }

Both of these strategies will yield the following:


hi hello good day

Set Properties and Methods

The following table shows a list of Set properties and methods for quick reference:

Properties/Methods Description Returns
Appends a new item to a Set
Removes the specified item from a Set Boolean
Checks for the presence of an item in a Set Boolean
Removes all items from a Set N/A
Returns all values in a Set (same as
Returns all values in a Set (same as
Returns all values in a Set as
Iterates through the Set in insertion order N/A
Returns the number of items in a Set Number

When to Use Set

Set is a useful addition to your JavaScript toolkit, particularly for working with duplicate values in data.

In a single line, we can create a new Array without duplicate values from an Array that has duplicate values.


const uniqueArray = [...new Set([1, 1, 2, 2, 2, 3])] // (3) [1, 2, 3]

This will give:


(3) [1, 2, 3]

Set can be used for finding the union, intersection, and difference between two sets of data. However, Arrays have a significant advantage over Sets for additional manipulation of the data due to the

sort()

,

map()

,

filter()

, and

reduce()

methods, as well as direct compatibility with

JSON

methods.

Javascript


let myMap =


new


Map().set(


'GFG'


, 1)


.set(


'Geeks'


, 2).set(


'Geeksforgeeks'


, 3);


let arr = [];


for


(let key of myMap.keys()) {


arr.push(key);


console.log(arr);

Output

[ ‘GFG’, ‘Geeks’, ‘Geeksforgeeks’ ]

  • Create an empty array
  • Use Map.forEach() method for iterating over the loop
  • then push the keys into an array

Example: This example shows the implementation of the above-explained approach.

JavaScript Google Maps API Tutorial Updated [2023] - Create Google Map 🗺️
JavaScript Google Maps API Tutorial Updated [2023] – Create Google Map 🗺️

What is a Map?

A map is another data structure/container used to store key-value pairs of data of any kind and length.

Maps are similar to objects, but with maps, you can use anything as a key. An object, on the other hand, takes strings, symbols, and numbers as keys.

Maps are iterables and come with various methods. Some of the features of maps are that the order is guaranteed, and values can be duplicated (but keys can’t).

Now we’ll learn more about each of these iterables so you understand how to use them.

Properties and Methods of a Set

Sets have several methods and a properties that you can use to retrieve, add, delete, check, and clear all the elements in the set. We will talk about all these methods and properties, and how to use them while working with the set.

How to use the add method in a set

We use the

add

method to add elements to the set. Create a set of fruits with 4 elements, it works like this:


const fruits = new Set(['apple'.'mango']); fruits.add('banana'); console.log(fruits)

From the above code, banana was added to the set with the help of the add method which gives us this result:


Set(3) {'apple'. 'mango', 'banana'}

Sets store unique elements, which means that adding another banana to the set won’t be accepted.

How to use the has method in a set

To check if an element is contained in a set, you’ll use the

has

method. In the code below, we’ll check if a fruit set with various elements contained a specific

banana

element.


const fruits = new Set(['apple','mango']); console.log(fruits.has('banana'));

This method will return false, because the element searched for is banana, which is not in the set. If it had been present, we would’ve gotten true back.

How to use the delete method in a set

You delete an item from a set using the “delete” method. The example below shows the “delete” method being used on a set of fruits containing 3 elements to delete one of the elements.


const fruits = new Set(['apple','mango', 'banana']); fruits.delete('apple'); console.log(fruits);

The code prints out a new set of 2 elemets. If you try deleting an element that is not in the set, it ignores it.


Set(2) {'mango', 'banana'};

How to use the clear method in a set

The clear method is used to clear all the elements in the set. With a set of fruits containing 3 elements, we use the delete method to delete one of the elements.


const fruits = new Set(['apple','mango', 'banana']); fruits.clear('apple'); console.log(fruits);

The code prints out a new set of 0 elements, as the clear method will return a set without any elements.


Set(0) {size : 0};

How to use the entries method in a set

You can retrieve all elements in a set using the “entries” method, which returns an iterable. You can then use a for loop or for-of loop to loop through the values.

The example below shows the creation of a set of fruits containing 5 elements, followed by the use of the “entries” method to loop through all elements of the array.


const fruits = new Set([100,160, 200,400,300]); for( const fruit of fruits.entries()){ console.log(fruit); }

It returns an iterable of arrays, each with two elements.


(2) {100, 100} (2) {160, 160} (2) {200, 200} (2) {400, 400} (2) {300, 300}

How to use the values method in a set

You retrieve the values in a set by using the “values” method, which returns an iterable. You can then use a for loop or for-of loop to loop through the values.

The example below shows the creation of a set of fruits with 4 elements and the use of the “values” method to loop through the elements with a for-of loop.


const fruits = new Set([100,160, 200,300]); for( const fruit of fruits.values()){ console.log(fruit); }

It returns an iterable, each with a single value:


100 160 200 300

How to use the size property in a set

You use the

size

property to determine the size of the set by returning the number of elements in it. To demonstrate this, we’ll create a set of fruits that contains 3 elements.


const fruits = new Set(['apple','mango','banana']); console.log(fruits.size);

The above code will return 3 as the size of the fruit set.

How to use forEach in a set

You can easily enumerate a set by using “forEach.” The example below shows the creation of a set of fruits with some elements, followed by the use of “forEach” to print each element of the set.


const fruits = new Set([100,160, 200,400,300]); fruits.forEach((fruit) => { console.log(fruit) });

The code prints each element of the set like this:


100 160 200 400 300

How to use a set to Get Unique Value from an Array.

You can remove duplicate values from an array by using a set. The example below shows the creation of an array of duplicated numbers, followed by passing the array into a set to get all unique numbers, free from duplicates.


const numbers = [1,2,4,1,6,8,2,5,9,2,0,9,7,6,3,4,6,7,8,4,2,1,5,8,9,0,2,4,5,3,2,6,8,9,6]; const numbers1 = new Set(numbers); console.log(numbers1);

The above code shows an array of numbers with different duplicated numbers. The array was then passed on to the set of numbers and the output is shown below.


Set(10) {1,2,4,6,8,5,9,0,7,3};

The code above shows that the set has removed all the duplicated numbers and now has a size of 10.

As you can see, set is a data structure that helps you manage unique values.

Map through State Array (Loop) - React tutorial 8
Map through State Array (Loop) – React tutorial 8

Instance properties

These properties are defined on

Map.prototype

and shared by all

Map

instances.


Map.prototype.constructor

The constructor function that created the instance object. For


Map

instances, the initial value is the

Map

constructor.


Map.prototype.size

Returns the number of key/value pairs in the


Map

object.


Map.prototype[@@toStringTag]

The initial value of the


@@toStringTag

property is the string

"Map"

. This property is used in

Object.prototype.toString()

.

Map.set()

You can add elements to a Map with the

set()

method:

Example

const fruits = new Map();

// Set Map Values

fruits.set(“apples”, 500);

fruits.set(“bananas”, 300);

fruits.set(“oranges”, 200);

The

set()

method can also be used to change existing Map values:

Example

Hash Tables - Beau teaches JavaScript
Hash Tables – Beau teaches JavaScript

Map.values()

The

values()

method returns an iterator object with the values in a Map:

Example

let text = “”;

for (const x of fruits.values()) {

text += x;

You can use the

values()

method to sum the values in a Map:

Example

let total = 0;

for (const x of fruits.values()) {

total += x;

JavaScript Objects vs Maps

Differences between JavaScript Objects and Maps:
Object Map
Not directly iterable Directly iterable
Do not have a size property Have a size property
Keys must be Strings (or Symbols) Keys can be any datatype
Keys are not well ordered Keys are ordered by insertion
Have default keys Do not have default keys
Map vs Object en JavaScript. ¿Qué son los Map y cuándo usarlos? 🤔
Map vs Object en JavaScript. ¿Qué son los Map y cuándo usarlos? 🤔

Examples

Using the Map object


const myMap = new Map(); const keyString = "a string"; const keyObj = {}; const keyFunc = function () {}; // setting the values myMap.set(keyString, "value associated with 'a string'"); myMap.set(keyObj, "value associated with keyObj"); myMap.set(keyFunc, "value associated with keyFunc"); console.log(myMap.size); // 3 // getting the values console.log(myMap.get(keyString)); // "value associated with 'a string'" console.log(myMap.get(keyObj)); // "value associated with keyObj" console.log(myMap.get(keyFunc)); // "value associated with keyFunc" console.log(myMap.get("a string")); // "value associated with 'a string'", because keyString === 'a string' console.log(myMap.get({})); // undefined, because keyObj !== {} console.log(myMap.get(function () {})); // undefined, because keyFunc !== function () {}

Using NaN as Map keys


NaN

can also be used as a key. Even though every

NaN

is
not equal to itself (

NaN !== NaN

is true), the following example works because

NaN

s are indistinguishable from each other:


const myMap = new Map(); myMap.set(NaN, "not a number"); myMap.get(NaN); // "not a number" const otherNaN = Number("foo"); myMap.get(otherNaN); // "not a number"

Iterating Map with for…of

Maps can be iterated using a

for...of

loop:


const myMap = new Map(); myMap.set(0, "zero"); myMap.set(1, "one"); for (const [key, value] of myMap) { console.log(`${key} = ${value}`); } // 0 = zero // 1 = one for (const key of myMap.keys()) { console.log(key); } // 0 // 1 for (const value of myMap.values()) { console.log(value); } // zero // one for (const [key, value] of myMap.entries()) { console.log(`${key} = ${value}`); } // 0 = zero // 1 = one

Iterating Map with forEach()

Maps can be iterated using the

forEach()

method:


myMap.forEach((value, key) => { console.log(`${key} = ${value}`); }); // 0 = zero // 1 = one

Relation with Array objects


const kvArray = [ ["key1", "value1"], ["key2", "value2"], ]; // Use the regular Map constructor to transform a 2D key-value Array into a map const myMap = new Map(kvArray); console.log(myMap.get("key1")); // "value1" // Use Array.from() to transform a map into a 2D key-value Array console.log(Array.from(myMap)); // Will show you exactly the same Array as kvArray // A succinct way to do the same, using the spread syntax console.log([...myMap]); // Or use the keys() or values() iterators, and convert them to an array console.log(Array.from(myMap.keys())); // ["key1", "key2"]

Cloning and merging Maps

Just like

Array

s,

Map

s can be cloned:


const original = new Map([[1, "one"]]); const clone = new Map(original); console.log(clone.get(1)); // one console.log(original === clone); // false (useful for shallow comparison)

Note: Keep in mind that the data itself is not cloned.

Maps can be merged, maintaining key uniqueness:


const first = new Map([ [1, "one"], [2, "two"], [3, "three"], ]); const second = new Map([ [1, "uno"], [2, "dos"], ]); // Merge two maps. The last repeated key wins. // Spread syntax essentially converts a Map to an Array const merged = new Map([...first, ...second]); console.log(merged.get(1)); // uno console.log(merged.get(2)); // dos console.log(merged.get(3)); // three

Maps can be merged with Arrays, too:


const first = new Map([ [1, "one"], [2, "two"], [3, "three"], ]); const second = new Map([ [1, "uno"], [2, "dos"], ]); // Merge maps with an array. The last repeated key wins. const merged = new Map([...first, ...second, [1, "eins"]]); console.log(merged.get(1)); // eins console.log(merged.get(2)); // dos console.log(merged.get(3)); // three

Javascript


const _ = require(


"lodash"


);


let myMap =


new


Map().set(


'GFG'


, 1).set(


'Geeks'


, 2);


let arr = _.toArray(myMap.keys());


console.log(arr.length);

Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Last Updated :
13 Dec, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

By Tania Rascia

The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

In 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 on, saving time and making code easier to comprehend. The two predominant data structures for storing collections of data are Objects and Arrays (a type of object). Developers use Objects to store key/value pairs and Arrays to store indexed lists. However, to give developers more flexibility, the ECMAScript 2015 specification introduced two new types of iterable objects: Maps, which are ordered collections of key/value pairs, and Sets, which are collections of unique values.

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

A Map is a collection of key/value pairs that can use any data type as a key and can maintain the order of its entries. Maps have elements of both Objects (a unique key/value pair collection) and Arrays (an ordered collection), but are more similar to Objects conceptually. This is because, although the size and order of entries is preserved like an Array, the entries themselves are key/value pairs like Objects.

Maps can be initialized with the

new Map()

syntax:


const map = new Map()

This gives us an empty Map:

OutputMap(0) {}

You can add values to a map with the

set()

method. The first argument will be the key, and the second argument will be the value.

The following adds three key/value pairs to

map

:


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

Here we begin to see how Maps have elements of both Objects and Arrays. Like an Array, we have a zero-indexed collection, and we can also see how many items are in the Map by default. Maps use the

=>

syntax to signify key/value pairs as

key => value

:

OutputMap(3) 0: {“firstName” => “Luke”} 1: {“lastName” => “Skywalker”} 2: {“occupation” => “Jedi Knight”}

This example looks similar to a regular object with string-based keys, but we can use any data type as a key with Maps.

In addition to manually setting values on a Map, we can also initialize a Map with values already. We do this using an Array of Arrays containing 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'], ])

Note: This example uses trailing commas, also referred to as dangling commas. This is a JavaScript formatting practice in which the final item in a series when declaring a collection of data has a comma at the end. Though this formatting choice can be used for cleaner diffs and easier code manipulation, whether to use it or not is a matter of preference. For more information on trailing commas, see this Trailing Comma article from the MDN web docs.

Incidentally, this syntax is the same as the result of calling

Object.entries()

on an Object. This provides a ready-made way to convert an Object to a Map, as shown in the following code block:


const luke = { firstName: 'Luke', lastName: 'Skywalker', occupation: 'Jedi Knight', } const map = new Map(Object.entries(luke))

Alternatively, you can turn a Map back into an Object or an Array with a single line of code.

The following converts a Map to an Object:


const obj = Object.fromEntries(map)

This will result in the following value of

obj

:

Output{firstName: “Luke”, lastName: “Skywalker”, occupation: “Jedi Knight”}

Now, let’s convert a Map to an Array:


const arr = Array.from(map)

This will result in the following Array for

arr

:

Output[ [‘firstName’, ‘Luke’], [‘lastName’, ‘Skywalker’], [‘occupation’, ‘Jedi Knight’] ]

Maps accept any data type as a key, and do not allow duplicate key values. We can demonstrate this by creating a map and using non-string values as keys, as well as setting two values to the same key.

First, let’s initialize a map with non-string keys:


const map = new Map() map.set('1', 'String one') map.set(1, 'This will be overwritten') map.set(1, 'Number one') map.set(true, 'A Boolean')

This example will override the first key of with the subsequent one, and it will treat

'1'

the string and the number as unique keys:

Output0: {“1” => “String one”} 1: {1 => “Number one”} 2: {true => “A Boolean”}

Although it is a common belief that a regular JavaScript Object can already handle Numbers, booleans, and other primitive data types as keys, this is actually not the case, because Objects change all keys to strings.

As an example, initialize an object with a numerical key and compare the value for a numerical key and a stringified

"1"

key:


// Initialize an object with a numerical key const obj = { 1: 'One' } // The key is actually a string obj[1] === obj['1'] // true

This is why if you attempt to use an Object as a key, it will print out the string

object Object

instead.

As an example, create an Object and then use it as the key of another Object:


// Create an object const objAsKey = { foo: 'bar' } // Use this object as the key of another object const obj = { [objAsKey]: 'What will happen?' }

This will yield the following:

Output{[object Object]: “What will happen?”}

This is not the case with Map. Try creating an Object and setting it as the key of a Map:


// Create an object const objAsKey = { foo: 'bar' } const map = new Map() // Set this object as the key of a Map map.set(objAsKey, 'What will happen?')

The

key

of the Map element is now the object we created.

Outputkey: {foo: “bar”} value: “What will happen?”

There is one important thing to note about using an Object or Array as a key: the Map is using the reference to the Object to compare equality, not the literal value of the Object. In JavaScript

{} === {}

returns

false

, because the two Objects are not the same two Objects, despite having the same (empty) value.

That means that adding two unique Objects with the same value will create a Map with two entries:


// Add two unique but similar objects as keys to a Map map.set({}, 'One') map.set({}, 'Two')

This will yield the following:

OutputMap(2) {{…} => “One”, {…} => “Two”}

But using the same Object reference twice will create a Map with one entry.


// Add the same exact object twice as keys to a Map const obj = {} map.set(obj, 'One') map.set(obj, 'Two')

Which will result in the following:

OutputMap(1) {{…} => “Two”}

The second

set()

is updating the same exact key as the first, so we end up with a Map that only has one value.

One of the disadvantages of working with Objects is that it can be difficult to enumerate them, or work with all the keys or values. The Map structure, by contrast, has a lot of built-in properties that make working with their elements more direct.

We can initialize a new Map to demonstrate the following methods and properties:

delete()

,

has()

,

get()

, and

size

.


// Initialize a new Map const map = new Map([ ['animal', 'otter'], ['shape', 'triangle'], ['city', 'New York'], ['country', 'Bulgaria'], ])

Use the

has()

method to check for the existence of an item in a map.

has()

will return a Boolean.


// Check if a key exists in a Map map.has('shark') // false map.has('country') // true

Use the

get()

method to retrieve a value by key.


// Get an item from a Map map.get('animal') // "otter"

One particular benefit Maps have over Objects is that you can find the size of a Map at any time, like you can with an Array. You can get the count of items in a Map with the

size

property. This involves fewer steps than converting an Object to an Array to find the length.


// Get the count of items in a Map map.size // 4

Use the

delete()

method to remove an item from a Map by key. The method will return a Boolean—

true

if an item existed and was deleted, and

false

if it did not match any item.


// Delete an item from a Map by key map.delete('city') // true

This will result in the following Map:

OutputMap(3) {“animal” => “otter”, “shape” => “triangle”, “country” => “Bulgaria”}

Finally, a Map can be cleared of all values with

map.clear()

.


// Empty a Map map.clear()

This will yield:

OutputMap(0) {}

Objects can retrieve keys, values, and entries by using the properties of the

Object

constructor. Maps, on the other hand, have prototype methods that allow us to get the keys, values, and entries of the Map instance directly.

The

keys()

,

values()

, and

entries()

methods all return a

MapIterator

, which is similar to an Array in that you can use

for...of

to loop through the values.

Here is another example of a Map, which we can use to demonstrate these methods:


const map = new Map([ [1970, 'bell bottoms'], [1980, 'leg warmers'], [1990, 'flannel'], ])

The

keys()

method returns the keys:


map.keys()

OutputMapIterator {1970, 1980, 1990}

The

values()

method returns the values:


map.values()

OutputMapIterator {“bell bottoms”, “leg warmers”, “flannel”}

The

entries()

method returns an array of key/value pairs:


map.entries()

OutputMapIterator {1970 => “bell bottoms”, 1980 => “leg warmers”, 1990 => “flannel”}

Map has a built-in

forEach

method, similar to an Array, for built-in iteration. However, there is a bit of a difference in what they iterate over. The callback of a Map’s

forEach

iterates through the

value

,

key

, and

map

itself, while the Array version iterates through the

item

,

index

, and

array

itself.


// Map Map.prototype.forEach((value, key, map) = () => {}) // Array Array.prototype.forEach((item, index, array) = () => {})

This is a big advantage for Maps over Objects, as Objects need to be converted with

keys()

,

values()

, or

entries()

, and there is not a simple way to retrieve the properties of an Object without converting it.

To demonstrate this, let’s iterate through our Map and log the key/value pairs to the console:


// Log the keys and values of the Map with forEach map.forEach((value, key) => { console.log(`${key}: ${value}`) })

This will give:

Output1970: bell bottoms 1980: leg warmers 1990: flannel

Since a

for...of

loop iterates over iterables like Map and Array, we can get the exact same result by destructuring the array of Map items:


// Destructure the key and value out of the Map item for (const [key, value] of map) { // Log the keys and values of the Map with for...of console.log(`${key}: ${value}`) }

The following table shows a list of Map properties and methods for quick reference:

Properties/Methods Description Returns
Appends a key/value pair to a Map
Removes a key/value pair from a Map by key Boolean
Returns a value by key value
Checks for the presence of an element in a Map by key Boolean
Removes all items from a Map N/A
Returns all keys in a Map
Returns all values in a Map
Returns all keys and values in a Map as
Iterates through the Map in insertion order N/A
Returns the number of items in a Map Number

Summing up, Maps are similar to Objects in that they hold key/value pairs, but Maps have several advantages over objects:


sizeproperty, whereas Objects do not have a built-in way to retrieve their size.

Due to these factors, Maps are a powerful data structure to consider. However, Objects haves some important advantages as well:


JSON.parse()and


JSON.stringify(), two essential functions for working with JSON, a common data format that many REST APIs deal with.


get().

This list will help you decide if a Map or Object is the right data structure for your use case.

A Set is a collection of unique values. Unlike a Map, a Set is conceptually more similar to an Array than an Object, since it is a list of values and not key/value pairs. However, Set is not a replacement for Arrays, but rather a supplement for providing additional support for working with duplicated data.

You can initialize Sets with the

new Set()

syntax.


const set = new Set()

This gives us an empty Set:

OutputSet(0) {}

Items can be added to a Set with the

add()

method. (This is not to be confused with the

set()

method available to Map, although they are similar.)


// Add items to a Set set.add('Beethoven') set.add('Mozart') set.add('Chopin')

Since Sets can only contain unique values, any attempt to add a value that already exists will be ignored.


set.add('Chopin') // Set will still contain 3 unique values

Note: The same equality comparison that applies to Map keys applies to Set items. Two objects that have the same value but do not share the same reference will not be considered equal.

You can also initialize Sets with an Array of values. If there are duplicate values in the array, they will be removed from the Set.


// Initialize a Set from an Array const set = new Set(['Beethoven', 'Mozart', 'Chopin', 'Chopin'])

OutputSet(3) {“Beethoven”, “Mozart”, “Chopin”}

Conversely, a Set can be converted into an Array with one line of code:


const arr = [...set]

Output(3) [“Beethoven”, “Mozart”, “Chopin”]

Set has many of the same methods and properties as Map, including

delete()

,

has()

,

clear()

, and

size

.


// Delete an item set.delete('Beethoven') // true // Check for the existence of an item set.has('Beethoven') // false // Clear a Set set.clear() // Check the size of a Set set.size // 0

Note that Set does not have a way to access a value by a key or index, like

Map.get(key)

or

arr[index]

.

Map and Set both have

keys()

,

values()

, and

entries()

methods that return an Iterator. However, while each one of these methods have a distinct purpose in Map, Sets do not have keys, and therefore keys are an alias for values. This means that

keys()

and

values()

will both return the same Iterator, and

entries()

will return the value twice. It makes the most sense to only use

values()

with Set, as the other two methods exist for consistency and cross-compatibility with Map.


const set = new Set([1, 2, 3]) // Get the values of a set set.values()

OutputSetIterator {1, 2, 3}

Like Map, Set has a built-in

forEach()

method. Since Sets don’t have keys, the first and second parameter of the

forEach()

callback return the same value, so there is no use case for it outside of compatibility with Map. The parameters of

forEach()

are

(value, key, set)

.

Both

forEach()

and

for...of

can be used on Set. First, let’s look at

forEach()

iteration:


const set = new Set(['hi', 'hello', 'good day']) // Iterate a Set with forEach set.forEach((value) => console.log(value))

Then we can write the

for...of

version:


// Iterate a Set with for...of for (const value of set) { console.log(value); }

Both of these strategies will yield the following:

Outputhi hello good day

The following table shows a list of Set properties and methods for quick reference:

Properties/Methods Description Returns
Appends a new item to a Set
Removes the specified item from a Set Boolean
Checks for the presence of an item in a Set Boolean
Removes all items from a Set N/A
Returns all values in a Set (same as
Returns all values in a Set (same as
Returns all values in a Set as
Iterates through the Set in insertion order N/A
Returns the number of items in a Set Number

Set is a useful addition to your JavaScript toolkit, particularly for working with duplicate values in data.

In a single line, we can create a new Array without duplicate values from an Array that has duplicate values.


const uniqueArray = [ ...new Set([1, 1, 2, 2, 2, 3])] // (3) [1, 2, 3]

This will give:

Output(3) [1, 2, 3]

Set can be used for finding the union, intersection, and difference between two sets of data. However, Arrays have a significant advantage over Sets for additional manipulation of the data due to the

sort()

,

map()

,

filter()

, and

reduce()

methods, as well as direct compatibility with

JSON

methods.

In this article, you learned that a Map is a collection of ordered key/value pairs, and that a Set is a collection of unique values. Both of these data structures add additional capabilities to JavaScript and simplify common tasks such as finding the length of a key/value pair collection and removing duplicate items from a data set, respectively. On the other hand, Objects and Arrays have been traditionally used for data storage and manipulation in JavaScript, and have direct compatibility with JSON, which continues to make them the most essential data structures, especially for working with REST APIs. Maps and Sets are primarily useful as supporting data structures for Objects and Arrays.

If you would like to learn more about JavaScript, check out the homepage for our How To Code in JavaScript series, or browse our How to Code in Node.js series for articles on back-end development.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

JavaScript is a high-level, object-based, dynamic scripting language popular as a tool for making webpages interactive.

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Excellent write-up!

hi, is there a way to get an item by index like in an array? for example, this doesn’t work: mymap[0]

in a map iterator object i am only able to get the next() element, but not directly the second or third, is there a way to get an item directly?

thanx, great article!

Understandable. Thank you for your work.

This is a great article from which I learned alot.

Thank you.

Click below to sign up and get $200 of credit to try our products over 60 days!

Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Map.prototype.values()

The

values()

method of

Map

instances returns a new map iterator object that contains the values for each element in this map in insertion order.

Maps vs. Objects in JavaScript - What's the Difference?
Maps vs. Objects in JavaScript – What’s the Difference?

Approach 1: Initialize a Map With Values in JavaScript Using set() Method

The “set()” is a map’s method that sets the key values in a map. This method can be utilized to set the map values in a “key-value” pair with the help of the created map object.

Example

Let’s overview the following example:

let initMap = new Map()

initMap.set(‘Name’, ‘Harry’)

initMap.set(‘Age’, ’18’)

initMap.set(‘City’, ‘Los Angeles’)

console.log(“The initialized map is:”, initMap)

In the above lines of code:

  • Create a new map object with the help of the “new” keyword and the “Map()” constructor, respectively.
  • In the next step, apply the map’s “set()” method to initialize the stated values in a “key-value” pair.
  • Lastly, display the initialized map values.

Output

In the above output, it can be observed that the map values are set accordingly.

Properties and Methods of Map

Map has several methods and properties that we can use to retrieve, add, delete, search, and clear all the elements in the map.

We will talk about all these methods and properties, and how to use them while working with map.

How to Get Values from the Map Object

Extracting data from map is easy using the get method. Let’s create an object of player1 with name and age properties. Then, the player1 object will be use as key in map. It works like this:


const player1 = { name: 'kamal', age: 30}; const playerData = new Map([[player1, [{date:'today',price :400}]]]); console.log(playerData);

In the above code, you can see that we used the

player1

object as a key in a Map in playerData. By using the get method, you can extract values from the player1 used as a key in the Map.


Map(1)

It returns a map of size 1. The map contains a key which is the player1 that we created above.


key :{ name : 'kamal', age : 30}

And it returns a value, which was an array of a single object that contains a date and price.


0: {date:'today', price:400}

How to Add Data with the set Method

You can add data to the Map after you create it with the help of the set method as shown below:


const player = new Map(); player.set('kamal','lawal'); console.log(player);

We added the key-value pair

kamal

and

lawal

to an empty map with the set method. The set method is where you set a key-value pair. The key has to be the first option and the value has to be the last. Both the key and values can be of any type of data.


Map(1) {'kamal' => 'lawal'}

How to Search an Element with the has Method

The

has

method returns true if the map contains keys that match the search term. We can create a map of

player

with two key-value pairs as shown below.


const player = new Map([['key','value'],['small','medium']]); console.log(player.has('small'));

The code will print true because the search term (

small

) is present in the map as a key.


true

But it will print false if the search term (

medium

) is present in the map not as a key but as a value.


const player = new Map([['key','value'],['small','medium']]); console.log(player.has('medium')); // output will be false, the searched term, (medium) is not a key but value

How to Delete an Element with the delete Method

We use the delete method to delete a specific element. Delete works if the searched term matches a key in an element. In this case, we’re deleting

small

.


const player = new Map([['key','value'],['small','medium']]); player.delete('small'); console.log(player);

The code will delete the key-value pair of

small

and

medium

. But, it won’t work if the search term is not a key in the map.


const player = new Map([['key','value'],['small','medium']]); player.delete('value'); console.log(player); // It won't work, because the search term is a value in the map

How to Clear All Elements with the clear Method

To clear all elements of a map, we’ll use the clear method.


const player = new Map([['key','value'],['small','medium']]); player.clear(); console.log(player);

The code will print an empty map as its output.


Map(0) { size : 0}

How to get all Entries in a Map with the entries Method

The entries method is one of the Map methods you can use with for or for-of loops directly because it returns

MapIterator

.

What is a MapIterator?

A MapIterator is an iterator returned by the

entries()

method of a JavaScript Map object. It returns an array-like object of key-value pairs, with each pair represented as an array containing 2 elements. The

MapIterator

can be used in a

for...of

loop to iterate over all key-value pairs in a Map object.

With

entries

, you can get all the data, both the key and value of a map.


const player = new Map([['key','value'],['small','medium'],['fruit','another']]); console.log(player.entries());

The values of all the keys and values will be logged as shown below:


MapIterator {'key' => 'value', 'small'=> 'medium', 'fruit' => 'another'}

How to Get All Keys in a Map with the keys Method

Aside from the

entries

method, the

keys

method also returns a

MapIterator

. With the keys method, you can get all the keys of a map, and it also runs a for or for-of loop:


const players = new Map([['key','value'],['small','medium'],['fruit','another']]); for(const player of players.keys()){ console.log(player); }

This will print all the keys in the map as an output, like this:


key small fruit

How to Get All Values in a Map with the values Method

The

values

method is the last map method that returns a

MapIterator

and you can run a for or for-of loop directly on it. This is the method you should use when getting only values in the map is the priority.


const players = new Map([['key','value'],['small','medium'],['fruit','another']]); for(const player of players.values()){ console.log(player); }

The output of the above code will be this:


value medium another

How to Enumerate Over a Map

For easy iteration in maps, you can use the popular

forEach

method as shown below:


const players = new Map([['key','value'],['small','medium'],['fruit','another']]); players.forEach((key, value) =>{ const message = `I want to be remeembered as the best ${key} pair ${value}`; console.log(message) })

The above code will print this as the output of the iteration:


I want to be remembered as the best value pair key I want to be remembered as the best medium pair small I want to be remembered as the best another pair fruit

How to Use Size Property in Map

You can use the property size to determine the size of the map by returning the number of elements in it.


const player = new Map([['key', 'value'],['small','medium'],['fruit','another']]); console.log(player.size);

This will print out 3 as the size of the map.

Map vs Object – What’s the Difference?

As you can see, a map is similar to an object which raises the question – when should you use each one?

When to use map:

  1. With map, you can use any type (and values) as keys.
  2. Map provides better performance for large quantities of data.
  3. Use a map for better performance when adding and removing data frequently.

When to use an object:

  1. Objects can only use numbers, strings, and symbols as keys.
  2. Objects are perfect for small to medium-sized sets of data.
  3. Objects have better performance and are easier to create.

Benefits of Sets over Arrays

Arrays and sets are both data structures used for storing collections of elements. But sets have a slight edge over arrays because of:

  • Uniqueness: With a set, duplicates are removed to reduce the size of the data structure (unlike an array which stores duplicates).
  • Manipulating collections: It is easy to combine a set with other sets to perform various operations like intersections, unions, and differences.
  • Performance: Because of the implementation using hash tables, set offers faster lookups and membership tests.
Update Knowledge - Js Hard Parts - Callbacks & HoF Transformation useful in React
Update Knowledge – Js Hard Parts – Callbacks & HoF Transformation useful in React

Useful JavaScript Map methods


  • clear()

    – removes all elements from the map object.

  • delete(key)

    – removes an element specified by the key. It returns if the element is in the map, or false if it does not.

  • entries()

    – returns a new Iterator object that contains an array of

    [key, value]

    for each element in the map object. The order of objects in the map is the same as the insertion order.

  • forEach(callback[, thisArg])

    – invokes a callback for each key-value pair in the map in the insertion order. The optional thisArg parameter sets the

    this

    value for each callback.
  • get(key) – returns the value associated with the key. If the key does not exist, it returns undefined.
  • has(key) – returns true if a value associated with the key exists or false otherwise.

  • keys()

    – returns a new Iterator that contains the keys for elements in insertion order.

  • set(key, value)

    – sets the value for the key in the map object. It returns the map object itself therefore you can chain this method with other methods.

  • values()

    returns a new iterator object that contains values for each element in insertion order.

Table of Contents

Maps in JavaScript are objects that represent a collection of key-value pairs.

What this means is that you can add new values by inserting them with a unique key.

However, you can alternatively just initialize the map with a set of key-value pairs if you already know what you want to store.

In this post, we’ll learn how to initialize a map with values in JavaScript.

JavaScript tips — Accessing value indexes in Array.map
JavaScript tips — Accessing value indexes in Array.map

Objects as Keys

Being able to use objects as keys is an important Map feature.

Example

const apples = {name: ‘Apples’};

const bananas = {name: ‘Bananas’};

const oranges = {name: ‘Oranges’};

// Create a Map

const fruits = new Map();

// Add new Elements to the Map

fruits.set(apples, 500);

fruits.set(bananas, 300);

fruits.set(oranges, 200);

Remember: The key is an object (apples), not a string (“apples”):

Example

Create a Map from an Object

Alternatively, another way to initialize a map is by passing in an object.

In general, objects in JavaScript are already key-value pairs, so it’s easy to use them to initialize a map.

All we need to do is use

Object.entries

on the object to convert it into an array of key-value pairs.

Let’s first create an example object:


const values = { name: "John", age: 30 };

Now we can use this to create a new map with the values:


const values = { name: "John", age: 30 }; const map = new Map(Object.entries(values)); console.log(map);


Map(2) {'name' => 'John', 'age' => 30}

Creating Maps from arrays and objects | Data Structure | JavaScript
Creating Maps from arrays and objects | Data Structure | JavaScript

Description


Map

objects are collections of key-value pairs. A key in the

Map

may only occur once; it is unique in the

Map

‘s collection. A

Map

object is iterated by key-value pairs — a

for...of

loop returns a 2-member array of

[key, value]

for each iteration. Iteration happens in insertion order, which corresponds to the order in which each key-value pair was first inserted into the map by the

set()

method (that is, there wasn’t a key with the same value already in the map when

set()

was called).

The specification requires maps to be implemented “that, on average, provide access times that are sublinear on the number of elements in the collection”. Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N).

Key equality

Value equality is based on the SameValueZero algorithm. (It used to use SameValue, which treated and

-0

as different. Check browser compatibility.) This means

NaN

is considered the same as

NaN

(even though

NaN !== NaN

) and all other values are considered equal according to the semantics of the

===

operator.

ObjectsMaps


Object

is similar to

Map

—both let you set keys to
values, retrieve those values, delete keys, and detect whether something is
stored at a key. For this reason (and because there were no built-in
alternatives),

Object

has been used as

Map

historically.

However, there are important differences that make

Map

preferable in some
cases:

Map Object
Accidental Keys

An

Note: This can be bypassed by using

Security

Setting user-provided key-value pairs on an

Key Types The keys of an
Key Order

The keys in

Although the keys of an ordinary

The order was first defined for own properties only in ECMAScript
2015; ECMAScript 2020 defines order for inherited properties as well.
But note that no single mechanism
iterates
all of an object’s properties; the various mechanisms
each include different subsets of properties.
(

Size

The number of items in a Determining the number of items in an
Iteration

Note:

Performance

Performs better in scenarios involving frequent additions and removals of key-value pairs.

Not optimized for frequent additions and removals of key-value pairs.

Serialization and parsing

No native support for serialization or parsing.

(But you can build your own serialization and parsing support for

Native support for serialization from

Native support for parsing from JSON to

Setting object properties

Setting Object properties works for Map objects as well, and can cause considerable confusion.

Therefore, this appears to work in a way:


const wrongMap = new Map(); wrongMap["bla"] = "blaa"; wrongMap["bla2"] = "blaaa2"; console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }

But that way of setting a property does not interact with the Map data structure. It uses the feature of the generic object. The value of ‘bla’ is not stored in the Map for queries. Other operations on the data fail:


wrongMap.has("bla"); // false wrongMap.delete("bla"); // false console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }

The correct usage for storing data in the Map is through the

set(key, value)

method.


const contacts = new Map(); contacts.set("Jessie", { phone: "213-555-1234", address: "123 N 1st Ave" }); contacts.has("Jessie"); // true contacts.get("Hilary"); // undefined contacts.set("Hilary", { phone: "617-555-4321", address: "321 S 2nd St" }); contacts.get("Jessie"); // {phone: "213-555-1234", address: "123 N 1st Ave"} contacts.delete("Raymond"); // false contacts.delete("Jessie"); // true console.log(contacts.size); // 1

Map-like browser APIs

Browser

Map

-like objects (or “maplike objects”) are Web API interfaces that behave in many ways like a

Map

.

Just like

Map

, entries can be iterated in the same order that they were added to the object.

Map

-like objects and

Map

also have properties and methods that share the same name and behavior.
However unlike

Map

they only allow specific predefined types for the keys and values of each entry.

The allowed types are set in the specification IDL definition.
For example,

RTCStatsReport

is a

Map

-like object that must use strings for keys and objects for values.
This is defined in the specification IDL below:


interface RTCStatsReport { readonly maplike

; };


Map

-like objects are either read-only or read-writable (see the

readonly

keyword in the IDL above).

  • Read-only

    Map

    -like objects have the property

    size

    , and the methods:

    entries()

    ,

    forEach()

    ,

    get()

    ,

    has()

    ,

    keys()

    ,

    values()

    , and

    @@iterator

    .
  • Writeable

    Map

    -like objects additionally have the methods:

    clear()

    ,

    delete()

    , and

    set()

    .

The methods and properties have the same behavior as the equivalent entities in

Map

, except for the restriction on the types of the keys and values.

The following are examples of read-only

Map

-like browser objects:

Approach 3: Initialize a Map With Values in JavaScript Using Array Approach

This approach can be implemented to create a map from the declared array.

Example

The below-given example explains the stated concept:

let initMap = new Map([

[‘Language’, ‘French’],

[‘Country’, ‘Germany’]

]);

console.log(“The initialized map is:”, initMap);

In the above code snippet:

  • Declare an array of the specified values.
  • This array will be contained in the created map object via the “Map()” constructor, as discussed.
  • Lastly, display the created map from an array.

Output

The above output signifies that the array is converted into the map.

Map in Javascript
Map in Javascript

How to Create a Map

You create a map by starting with the “new” keyword followed by “map.” The example below shows the creation of a map of a player, which returns an empty map. You can create a new map like this:


const player = new Map(); console.log(player);

And it returns a map with an empty value.


Map(0) {size : 0}

You can also create a map using a constructor initialized with an array of arrays. Each array in the array is one key-value pair, and the key can be of any type. The example below shows the creation of a map of two arrays using the constructor.


const player = new Map([['key','value'],['lawal','kamal']]); console.log(player);

The above code returns a map with two elements:


Map(2) { 'key' => 'value', 'lawal' => 'kamal'}


key

and

lawal

are the keys of the map, while

value

and

kamal

are the values.

Instance methods


Map.prototype.clear()

Removes all key-value pairs from the


Map

object.


Map.prototype.delete()

Returns


true

if an element in the

Map

object existed and has been removed, or

false

if the element does not exist.

map.has(key)

will return

false

afterwards.


Map.prototype.entries()

Returns a new Iterator object that contains a two-member array of


[key, value]

for each element in the

Map

object in insertion order.


Map.prototype.forEach()

Calls


callbackFn

once for each key-value pair present in the

Map

object, in insertion order. If a

thisArg

parameter is provided to

forEach

, it will be used as the

this

value for each callback.


Map.prototype.get()

Returns the value associated to the passed key, or


undefined

if there is none.


Map.prototype.has()

Returns a boolean indicating whether a value has been associated with the passed key in the


Map

object or not.


Map.prototype.keys()

Returns a new Iterator object that contains the keys for each element in the


Map

object in insertion order.


Map.prototype.set()

Sets the value for the passed key in the


Map

object. Returns the

Map

object.


Map.prototype.values()

Returns a new Iterator object that contains the values for each element in the


Map

object in insertion order.


Map.prototype[@@iterator]()

Returns a new Iterator object that contains a two-member array of


[key, value]

for each element in the

Map

object in insertion order.

JavaScript Array Map
JavaScript Array Map

Conclusion

In this article, you learned that a Map is a collection of ordered key/value pairs, and that a Set is a collection of unique values. Both of these data structures add additional capabilities to JavaScript and simplify common tasks such as finding the length of a key/value pair collection and removing duplicate items from a data set, respectively. On the other hand, Objects and Arrays have been traditionally used for data storage and manipulation in JavaScript, and have direct compatibility with JSON, which continues to make them the most essential data structures, especially for working with REST APIs. Maps and Sets are primarily useful as supporting data structures for Objects and Arrays.

If you would like to learn more about JavaScript, check out the homepage for our How To Code in JavaScript series, or browse our How to Code in Node.js series for articles on back-end development.

Map

The

Map

object holds key-value pairs and remembers the original insertion order of the keys.
Any value (both objects and primitive values) may be used as either a key or a value.

Object.fromEntries: Object from Map

We’ve just seen how to create

Map

from a plain object with

Object.entries(obj)

.

There’s

Object.fromEntries

method that does the reverse: given an array of

[key, value]

pairs, it creates an object from them:

We can use

Object.fromEntries

to get a plain object from

Map

.

E.g. we store the data in a

Map

, but we need to pass it to a 3rd-party code that expects a plain object.

Here we go:

A call to

map.entries()

returns an iterable of key/value pairs, exactly in the right format for

Object.fromEntries

.

We could also make line

(*)

shorter:


let obj = Object.fromEntries(map); // omit .entries()

That’s the same, because

Object.fromEntries

expects an iterable object as the argument. Not necessarily an array. And the standard iteration for

map

returns same key/value pairs as

map.entries()

. So we get a plain object with same key/values as the

map

.

#33 Maps and Weak Maps | JavaScript Full Tutorial
#33 Maps and Weak Maps | JavaScript Full Tutorial

Map

Map is a collection of keyed data items, just like an

Object

. But the main difference is that

Map

allows keys of any type.

Methods and properties are:


  • new Map()

    – creates the map.

  • 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 element (the key/value pair) by the key.

  • map.clear()

    – removes everything from the map.

  • map.size

    – returns the current element count.

For instance:


let map = new Map(); map.set('1', 'str1'); // a string key map.set(1, 'num1'); // a numeric key map.set(true, 'bool1'); // a boolean key // remember the regular Object? it would convert keys to string // Map keeps the type, so these two are different: alert( map.get(1) ); // 'num1' alert( map.get('1') ); // 'str1' alert( map.size ); // 3

As we can see, unlike objects, keys are not converted to strings. Any type of key is possible.


map[key]isn’t the right way to use a


Map

Although

map[key]

also works, e.g. we can set

map[key] = 2

, this is treating

map

as a plain JavaScript object, so it implies all corresponding limitations (only string/symbol keys and so on).

So we should use

map

methods:

set

,

get

and so on.

Map can also use objects as keys.

For instance:

Using objects as keys is one of the most notable and important

Map

features. The same does not count for

Object

. String as a key in

Object

is fine, but we can’t use another

Object

as a key in

Object

.

Let’s try:


let john = { name: "John" }; let ben = { name: "Ben" }; let visitsCountObj = {}; // try to use an object visitsCountObj[ben] = 234; // try to use ben object as the key visitsCountObj[john] = 123; // try to use john object as the key, ben object will get replaced // That's what got written! alert( visitsCountObj["[object Object]"] ); // 123

As

visitsCountObj

is an object, it converts all

Object

keys, such as

john

and

ben

above, to same string

"[object Object]"

. Definitely not what we want.


Mapcompares keys

To test keys for equivalence,

Map

uses the algorithm SameValueZero. It is roughly the same as strict equality

===

, but the difference is that

NaN

is considered equal to

NaN

. So

NaN

can be used as the key as well.

This algorithm can’t be changed or customized.

Every

map.set

call returns the map itself, so we can “chain” the calls:


map.set('1', 'str1') .set(1, 'num1') .set(true, 'bool1');

Browser Support

JavaScript Maps are supported in all browsers, except Internet Explorer:

Chrome Edge Firefox Safari Opera

Understanding Map and Set in JavaScript

This article was originally written for DigitalOcean.

In 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 on, saving time and making code easier to comprehend. The two predominant data structures for storing collections of data are Objects and Arrays (a type of object). Developers use Objects to store key/value pairs and Arrays to store indexed lists. However, to give developers more flexibility, the ECMAScript 2015 specification introduced two new types of iterable objects: Maps, which are ordered collections of key/value pairs, and Sets, which are collections of unique values.

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

Maps in javascript
Maps in javascript

Browser compatibility

BCD tables only load in the browser

Understanding Map and Set in JavaScript

This article was originally written for DigitalOcean.

In 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 on, saving time and making code easier to comprehend. The two predominant data structures for storing collections of data are Objects and Arrays (a type of object). Developers use Objects to store key/value pairs and Arrays to store indexed lists. However, to give developers more flexibility, the ECMAScript 2015 specification introduced two new types of iterable objects: Maps, which are ordered collections of key/value pairs, and Sets, which are collections of unique values.

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

How to Create a Set

Since we use sets to create unique values, an ID is a perfect example of something to create with a set. We can create a new set like this:


const ids = new Set();

To create a set, you start with the

new

keyword along with

set

. In the above code, we created a set of ids which returns an empty set.


Set(0) {size: 0}

How to Create a Set with a Value

You initialize the set with an iterable by creating a set with some initial value. An iterable such as an array, set, or nodelist can be passed to the set. The example below shows a set created from an array of 4 elements.


const ids = new Set([3,6,9,7]); console.log(ids);

The output will be like this:


Set(4) {3,6,9,7}

From the result, the code returns a set with 4 elements.

map Array Method | JavaScript Tutorial
map Array Method | JavaScript Tutorial

Conclusion

In this post, we learned how to initialize a map with values in JavaScript by starting with an array or object.

Both of these approaches are good for when you already have the values you want in the map.

Thanks for reading and happy coding!

  • Managing PHP Dependencies with Composer
  • Getting Started with Express
  • How to Serve Static Files with Nginx and Docker
  • How to deploy a .NET app using Docker
  • How to deploy a Deno app using Docker
  • Getting Started with Deno
  • Learn how to use v-model with a custom Vue component
  • How to Scrape the Web using Node.js and Puppeteer
  • Build a Real-Time Chat App with Node, Express, and Socket.io
  • Getting Started with Moment.js
  • Using Push.js to Display Web Browser Notifications
  • Building a Real-Time Note-Taking App with Vue and Firebase

JavaScript Maps

A Map holds key-value pairs where the keys can be any datatype.

A Map remembers the original insertion order of the keys.

A Map has a property that represents the size of the map.

Description


Map

objects are collections of key-value pairs. A key in the

Map

may only occur once; it is unique in the

Map

‘s collection. A

Map

object is iterated by key-value pairs — a

for...of

loop returns a 2-member array of

[key, value]

for each iteration. Iteration happens in insertion order, which corresponds to the order in which each key-value pair was first inserted into the map by the

set()

method (that is, there wasn’t a key with the same value already in the map when

set()

was called).

The specification requires maps to be implemented “that, on average, provide access times that are sublinear on the number of elements in the collection”. Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N).

Key equality

Value equality is based on the SameValueZero algorithm. (It used to use SameValue, which treated and

-0

as different. Check browser compatibility.) This means

NaN

is considered the same as

NaN

(even though

NaN !== NaN

) and all other values are considered equal according to the semantics of the

===

operator.

ObjectsMaps


Object

is similar to

Map

—both let you set keys to
values, retrieve those values, delete keys, and detect whether something is
stored at a key. For this reason (and because there were no built-in
alternatives),

Object

has been used as

Map

historically.

However, there are important differences that make

Map

preferable in some
cases:

Map Object
Accidental Keys

An

Note: This can be bypassed by using

Security

Setting user-provided key-value pairs on an

Key Types The keys of an
Key Order

The keys in

Although the keys of an ordinary

The order was first defined for own properties only in ECMAScript
2015; ECMAScript 2020 defines order for inherited properties as well.
But note that no single mechanism
iterates
all of an object’s properties; the various mechanisms
each include different subsets of properties.
(

Size

The number of items in a Determining the number of items in an
Iteration

Note:

Performance

Performs better in scenarios involving frequent additions and removals of key-value pairs.

Not optimized for frequent additions and removals of key-value pairs.

Serialization and parsing

No native support for serialization or parsing.

(But you can build your own serialization and parsing support for

Native support for serialization from

Native support for parsing from JSON to

Setting object properties

Setting Object properties works for Map objects as well, and can cause considerable confusion.

Therefore, this appears to work in a way:


const wrongMap = new Map(); wrongMap["bla"] = "blaa"; wrongMap["bla2"] = "blaaa2"; console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }

But that way of setting a property does not interact with the Map data structure. It uses the feature of the generic object. The value of ‘bla’ is not stored in the Map for queries. Other operations on the data fail:


wrongMap.has("bla"); // false wrongMap.delete("bla"); // false console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }

The correct usage for storing data in the Map is through the

set(key, value)

method.


const contacts = new Map(); contacts.set("Jessie", { phone: "213-555-1234", address: "123 N 1st Ave" }); contacts.has("Jessie"); // true contacts.get("Hilary"); // undefined contacts.set("Hilary", { phone: "617-555-4321", address: "321 S 2nd St" }); contacts.get("Jessie"); // {phone: "213-555-1234", address: "123 N 1st Ave"} contacts.delete("Raymond"); // false contacts.delete("Jessie"); // true console.log(contacts.size); // 1

Map-like browser APIs

Browser

Map

-like objects (or “maplike objects”) are Web API interfaces that behave in many ways like a

Map

.

Just like

Map

, entries can be iterated in the same order that they were added to the object.

Map

-like objects and

Map

also have properties and methods that share the same name and behavior.
However unlike

Map

they only allow specific predefined types for the keys and values of each entry.

The allowed types are set in the specification IDL definition.
For example,

RTCStatsReport

is a

Map

-like object that must use strings for keys and objects for values.
This is defined in the specification IDL below:


interface RTCStatsReport { readonly maplike

; };


Map

-like objects are either read-only or read-writable (see the

readonly

keyword in the IDL above).

  • Read-only

    Map

    -like objects have the property

    size

    , and the methods:

    entries()

    ,

    forEach()

    ,

    get()

    ,

    has()

    ,

    keys()

    ,

    values()

    , and

    @@iterator

    .
  • Writeable

    Map

    -like objects additionally have the methods:

    clear()

    ,

    delete()

    , and

    set()

    .

The methods and properties have the same behavior as the equivalent entities in

Map

, except for the restriction on the types of the keys and values.

The following are examples of read-only

Map

-like browser objects:

JavaScript Data Structures - 5 - Map
JavaScript Data Structures – 5 – Map

Instance properties

These properties are defined on

Map.prototype

and shared by all

Map

instances.


Map.prototype.constructor

The constructor function that created the instance object. For


Map

instances, the initial value is the

Map

constructor.


Map.prototype.size

Returns the number of key/value pairs in the


Map

object.


Map.prototype[@@toStringTag]

The initial value of the


@@toStringTag

property is the string

"Map"

. This property is used in

Object.prototype.toString()

.

Set

A Set is a collection of unique values. Unlike a Map, a Set is conceptually more similar to an Array than an Object, since it is a list of values and not key/value pairs. However, Set is not a replacement for Arrays, but rather a supplement for providing additional support for working with duplicated data.

You can initialize Sets with the

new Set()

syntax.


const set = new Set()

This gives us an empty Set:


Set(0) {}

Items can be added to a Set with the

add()

method. (This is not to be confused with the

set()

method available to Map, although they are similar.)


// Add items to a Set set.add('Beethoven') set.add('Mozart') set.add('Chopin')

Since Sets can only contain unique values, any attempt to add a value that already exists will be ignored.


set.add('Chopin') // Set will still contain 3 unique values

Note: The same equality comparison that applies to Map keys applies to Set items. Two objects that have the same value but do not share the same reference will not be considered equal.

You can also initialize Sets with an Array of values. If there are duplicate values in the array, they will be removed from the Set.


// Initialize a Set from an Array const set = new Set(['Beethoven', 'Mozart', 'Chopin', 'Chopin'])


Set(3) {"Beethoven", "Mozart", "Chopin"}

Conversely, a Set can be converted into an Array with one line of code:


const arr = [...set]


(3) ["Beethoven", "Mozart", "Chopin"]

Set has many of the same methods and properties as Map, including

delete()

,

has()

,

clear()

, and

size

.


// Delete an item set.delete('Beethoven') // true // Check for the existence of an item set.has('Beethoven') // false // Clear a Set set.clear() // Check the size of a Set set.size // 0

Note that Set does not have a way to access a value by a key or index, like

Map.get(key)

or

arr[index]

.

Keys, Values, and Entries for Sets

Map and Set both have

keys()

,

values()

, and

entries()

methods that return an Iterator. However, while each one of these methods have a distinct purpose in Map, Sets do not have keys, and therefore keys are an alias for values. This means that

keys()

and

values()

will both return the same Iterator, and

entries()

will return the value twice. It makes the most sense to only use

values()

with Set, as the other two methods exist for consistency and cross-compatibility with Map.


const set = new Set([1, 2, 3]) // Get the values of a set set.values()


SetIterator {1, 2, 3}

Iteration with Set

Like Map, Set has a built-in

forEach()

method. Since Sets don’t have keys, the first and second parameter of the

forEach()

callback return the same value, so there is no use case for it outside of compatibility with Map. The parameters of

forEach()

are

(value, key, set)

.

Both

forEach()

and

for...of

can be used on Set. First, let’s look at

forEach()

iteration:


const set = new Set(['hi', 'hello', 'good day']) // Iterate a Set with forEach set.forEach((value) => console.log(value))

Then we can write the

for...of

version:


// Iterate a Set with for...of for (const value of set) { console.log(value) }

Both of these strategies will yield the following:


hi hello good day

Set Properties and Methods

The following table shows a list of Set properties and methods for quick reference:

Properties/Methods Description Returns
Appends a new item to a Set
Removes the specified item from a Set Boolean
Checks for the presence of an item in a Set Boolean
Removes all items from a Set N/A
Returns all values in a Set (same as
Returns all values in a Set (same as
Returns all values in a Set as
Iterates through the Set in insertion order N/A
Returns the number of items in a Set Number

When to Use Set

Set is a useful addition to your JavaScript toolkit, particularly for working with duplicate values in data.

In a single line, we can create a new Array without duplicate values from an Array that has duplicate values.


const uniqueArray = [...new Set([1, 1, 2, 2, 2, 3])] // (3) [1, 2, 3]

This will give:


(3) [1, 2, 3]

Set can be used for finding the union, intersection, and difference between two sets of data. However, Arrays have a significant advantage over Sets for additional manipulation of the data due to the

sort()

,

map()

,

filter()

, and

reduce()

methods, as well as direct compatibility with

JSON

methods.

Maps - Javascript In Depth
Maps – Javascript In Depth

Examples

Using the Map object


const myMap = new Map(); const keyString = "a string"; const keyObj = {}; const keyFunc = function () {}; // setting the values myMap.set(keyString, "value associated with 'a string'"); myMap.set(keyObj, "value associated with keyObj"); myMap.set(keyFunc, "value associated with keyFunc"); console.log(myMap.size); // 3 // getting the values console.log(myMap.get(keyString)); // "value associated with 'a string'" console.log(myMap.get(keyObj)); // "value associated with keyObj" console.log(myMap.get(keyFunc)); // "value associated with keyFunc" console.log(myMap.get("a string")); // "value associated with 'a string'", because keyString === 'a string' console.log(myMap.get({})); // undefined, because keyObj !== {} console.log(myMap.get(function () {})); // undefined, because keyFunc !== function () {}

Using NaN as Map keys


NaN

can also be used as a key. Even though every

NaN

is
not equal to itself (

NaN !== NaN

is true), the following example works because

NaN

s are indistinguishable from each other:


const myMap = new Map(); myMap.set(NaN, "not a number"); myMap.get(NaN); // "not a number" const otherNaN = Number("foo"); myMap.get(otherNaN); // "not a number"

Iterating Map with for…of

Maps can be iterated using a

for...of

loop:


const myMap = new Map(); myMap.set(0, "zero"); myMap.set(1, "one"); for (const [key, value] of myMap) { console.log(`${key} = ${value}`); } // 0 = zero // 1 = one for (const key of myMap.keys()) { console.log(key); } // 0 // 1 for (const value of myMap.values()) { console.log(value); } // zero // one for (const [key, value] of myMap.entries()) { console.log(`${key} = ${value}`); } // 0 = zero // 1 = one

Iterating Map with forEach()

Maps can be iterated using the

forEach()

method:


myMap.forEach((value, key) => { console.log(`${key} = ${value}`); }); // 0 = zero // 1 = one

Relation with Array objects


const kvArray = [ ["key1", "value1"], ["key2", "value2"], ]; // Use the regular Map constructor to transform a 2D key-value Array into a map const myMap = new Map(kvArray); console.log(myMap.get("key1")); // "value1" // Use Array.from() to transform a map into a 2D key-value Array console.log(Array.from(myMap)); // Will show you exactly the same Array as kvArray // A succinct way to do the same, using the spread syntax console.log([...myMap]); // Or use the keys() or values() iterators, and convert them to an array console.log(Array.from(myMap.keys())); // ["key1", "key2"]

Cloning and merging Maps

Just like

Array

s,

Map

s can be cloned:


const original = new Map([[1, "one"]]); const clone = new Map(original); console.log(clone.get(1)); // one console.log(original === clone); // false (useful for shallow comparison)

Note: Keep in mind that the data itself is not cloned.

Maps can be merged, maintaining key uniqueness:


const first = new Map([ [1, "one"], [2, "two"], [3, "three"], ]); const second = new Map([ [1, "uno"], [2, "dos"], ]); // Merge two maps. The last repeated key wins. // Spread syntax essentially converts a Map to an Array const merged = new Map([...first, ...second]); console.log(merged.get(1)); // uno console.log(merged.get(2)); // dos console.log(merged.get(3)); // three

Maps can be merged with Arrays, too:


const first = new Map([ [1, "one"], [2, "two"], [3, "three"], ]); const second = new Map([ [1, "uno"], [2, "dos"], ]); // Merge maps with an array. The last repeated key wins. const merged = new Map([...first, ...second, [1, "eins"]]); console.log(merged.get(1)); // eins console.log(merged.get(2)); // dos console.log(merged.get(3)); // three

WeakMap

A

WeakMap

is similar to a

Map

except for the keys of a

WeakMap

must be objects. It means that when a reference to a key (an object) is out of scope, the corresponding value is automatically released from the memory.

A

WeakMap

only has subset methods of a

Map

object:


  • get(key)

  • set(key, value)

  • has(key)

  • delete(key)

Here are the main differences between a

Map

and a

WeekMap

:

  • Elements of a WeakMap cannot be iterated.
  • Cannot clear all elements at once.
  • Cannot check the size of a WeakMap.

In this tutorial, you have learned how to work with the JavaScript Map object and its useful methods to manipulate entries in the map.

Map vs Object in JavaScript
Map vs Object in JavaScript

Conclusion

In this article, you learned that a Map is a collection of ordered key/value pairs, and that a Set is a collection of unique values. Both of these data structures add additional capabilities to JavaScript and simplify common tasks such as finding the length of a key/value pair collection and removing duplicate items from a data set, respectively. On the other hand, Objects and Arrays have been traditionally used for data storage and manipulation in JavaScript, and have direct compatibility with JSON, which continues to make them the most essential data structures, especially for working with REST APIs. Maps and Sets are primarily useful as supporting data structures for Objects and Arrays.

If you would like to learn more about JavaScript, check out the homepage for our How To Code in JavaScript series, or browse our How to Code in Node.js series for articles on back-end development.

Till now, we’ve learned about the following complex data structures:

  • Objects are used for storing keyed collections.
  • Arrays are used for storing ordered collections.

But that’s not enough for real life. That’s why

Map

and

Set

also exist.

Keywords searched by users: javascript new map with values

Map In Javascript And When It'S A Better Choice Than Object - Js Curious
Map In Javascript And When It’S A Better Choice Than Object – Js Curious
Javascript Map Object Iterating Over Keys & Values - Youtube
Javascript Map Object Iterating Over Keys & Values – Youtube
Javascript Map And Set Explained - Youtube
Javascript Map And Set Explained – Youtube
Map And Set In Javascript - Scaler Topics
Map And Set In Javascript – Scaler Topics
Javascript Object Features In Typescript — Maps And Sets
Javascript Object Features In Typescript — Maps And Sets
How To Sort A Map By Key Value In Javascript - Youtube
How To Sort A Map By Key Value In Javascript – Youtube
How To Convert Map Values To An Array In Javascript
How To Convert Map Values To An Array In Javascript
Map In Javascript | Learn The Different Map Methods In Javascript
Map In Javascript | Learn The Different Map Methods In Javascript

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *