Exploring Map in JavaScript: Examples and Use Cases


In JavaScript, a Map is a collection of key-value pairs, where each key is unique, and it can hold any type of values like objects, primitives, and other maps. In this code, we will learn about various methods and properties of the Map object in JavaScript.

The common functions associated with the Map object in JavaScript:

Method Description
Map.prototype.clear() Removes all key-value pairs from the map.
Map.prototype.delete(key) Removes the entry with the specified key from the map.
Map.prototype.entries() Returns an iterator object that contains an array of [key, value] pairs for each element.
Map.prototype.forEach(callbackFn) Calls the specified function once for each key-value pair in the map.
Map.prototype.get(key) Returns the value associated with the specified key in the map.
Map.prototype.has(key) Returns a Boolean indicating whether the specified key is present in the map.
Map.prototype.keys() Returns an iterator object that contains the keys for each element in the map.
Map.prototype.set(key, value) Sets the value for the specified key in the map.
Map.prototype.values() Returns an iterator object that contains the values for each element in the map.

Creating a Map Object:

To create a new Map object, we use the Map() constructor function. The code initializes an empty Map object and assigns it to the variable userMap:

const userMap = new Map();

Adding Elements to a Map:

To add a new key-value pair to the Map, we use the set() method. The following code adds four key-value pairs to the userMap:

userMap.set("name", "Joes"); 
userMap.set("age", 30); 
userMap.set("city", "Salem"); 
userMap.set("contact", "9043017689");

Printing a Map Object:

To print a Map object, we can simply log it to the console. The following code logs the userMap to the console:

console.log(userMap);

Updating the Value of a Map:

To update the value of an existing key in the Map, we can simply use the set() method again with the same key. The following code updates the age of the user in the userMap:

userMap.set("age", 31); 
console.log(userMap);

Map Size:

To get the size of a Map object, we can use the size property. The following code logs the size of the userMap:

console.log("Map Size: ", userMap.size);

Deleting a Key-Value Pair from a Map:

To remove a key-value pair from the Map, we can use the delete() method. The following code removes the city from the userMap:

console.log("Before Delete :", userMap);
userMap.delete("city"); 
console.log("After Delete :", userMap);

Retrieving a Value from a Map:

To retrieve the value of a key from the Map, we can use the get() method. The following code retrieves the value of the name key from the userMap:

console.log(userMap.get("name"));

Checking if a Key Exists in a Map:

To check if a key exists in the Map, we can use the has() method. The following code checks if the name and city keys exist in the userMap:

console.log(userMap.has("name")); 
console.log(userMap.has("city"));

Iterating a Map with for...of:

We can iterate over the keys and values of a Map using a for...of loop with destructuring. The following code logs each key-value pair of the userMap to the console:

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

Retrieving Keys from a Map:

We can retrieve all the keys of a Map using the keys() method. The following code logs each key of the userMap to the console:

for (const key of userMap.keys()) 
{ 
console.log(key); 
}

Retrieving Values from a Map:

We can retrieve all the values of a Map using thevalues() method. The following code logs each value of the userMap to the console:

for (const value of userMap.values()) 
{ 
   console.log(value); 
}

Retrieving Entries from a Map:

We can retrieve all the entries of a Map using theentries() method. The following code logs each entry of the userMap to the console:

for (const value of userMap.entries ()) 
{ 
   console.log(`${key}  = ${value}`); 
}

This code snippet uses the entries() method of a Map object to iterate over its key-value pairs and log them to the console. Here's how it works:

  • The entries() method returns an iterator object which iterates over the Map's key-value pairs. Each iteration returns an array with two elements: the key and the value of the current pair.
  • The for...of loop is used to iterate over the iterator and execute a block of code for each iteration. Inside the loop, we use array destructuring to assign the key and value of the current pair to the variables key and value, respectively.

Finally, we log the key-value pair to the console using string interpolation with a template literal.

Retrieving Key-value from a Map using forEach():

We can retrieve all the key-value of a Map using theforEach() method. The following code logs each key-value of the userMap to the console:

userMap.forEach((value, key) => {
  console.log(`${key}  = ${value}`);
});

This code snippet uses the forEach() method of a Map object to iterate over its key-value pairs and log them to the console. Here's how it works:

  • The forEach() method takes a callback function as its argument, which is executed for each key-value pair in the Map. The callback function receives two arguments: the value of the current pair, followed by its key.
  • Inside the callback function, we log the key-value pair to the console using string interpolation with a template literal.

Overall, this code snippet accomplishes the same thing as the previous one (iterating over a Map's key-value pairs and logging them to the console), but uses the forEach() method instead of a for...of loop with the entries() method. Both approaches are valid and have their own advantages depending on the situation.

Clear all values from a Map:

The clear() method is a built-in method of the Map object in JavaScript. It is used to remove all key-value pairs from a Map object. Here are some examples of how the clear() method can be used with Map:

userMap.clear();
console.log("After Clear :", userMap);

This code snippet calls the clear() method on a Map object, which removes all key-value pairs from the Map. Here's how it works:

  • The clear() method is a built-in method of a Map object that removes all key-value pairs from the Map. After calling this method, the Map will be empty.
  • After calling clear(), the code logs a message to the console with the contents of the Map. Since the Map has been cleared, the output will show an empty Map object.

Overall, this code snippet demonstrates how to use the clear() method to remove all key-value pairs from a Map object. It can be useful when you want to reset the Map to an empty state.

Relation with Array objects

In JavaScript, a Map object is a collection of key-value pairs that allows keys of any type, including objects, to be used as keys. A Map object can be created from an array of arrays, where each sub-array contains two elements, the key and the value. Here's an example:

const arr = [
  ["key1", "value1"],
  ["key2", "value2"],
];
const myMap = new Map(arr);
console.log(myMap);
console.log(myMap.get("key1"));

In the above code, an array of arrays arr is created, where each sub-array contains a key-value pair. A Map object myMap is created from the array arr. The console.log statements print the Map object and the value associated with the key "key1". To convert a Map object to an array, we can use the Array.from() method. Here's an example:

console.log(Array.from(myMap));

The Array.from() method creates a new array from an array-like object, which in this case is the Map object myMap. The resulting array will contain arrays with two elements, the key and the value.In summary, the above code shows how to create a Map object from an array of arrays and how to convert a Map object to an array using the Array.from() method. This can be useful when working with collections of key-value pairs in JavaScript.

The spread operator (...) can be used to spread the elements of an iterable object, such as an array or a Map object, into a new array or object. When used with a Map object, the spread operator creates an array of arrays containing the key-value pairs of the Map object.

Here's an example:

console.log([...myMap]);

In the above code, the spread operator is used to create a new array containing the key-value pairs of the Map object myMap.

To create an array of the keys or values of a Map object, we can use the Map.prototype.keys() or Map.prototype.values() methods, respectively. These methods return an iterable object that can be converted to an array using the Array.from() method.

Here are examples of how to create arrays of the keys and values of a Map object:

console.log(Array.from(myMap.keys()));
console.log(Array.from(myMap.values()));

In the above code, the Array.from() method is used to convert the iterable objects returned by myMap.keys() and myMap.values() to arrays.In summary, the spread operator can be used to create an array of arrays containing the key-value pairs of a Map object, while the Map.prototype.keys() and Map.prototype.values() methods can be used to create arrays of the keys or values of a Map object.

Using Maps in JavaScript: Common Mistakes and Best Practices

Maps are a useful data structure in JavaScript that allow you to store key-value pairs. They are similar to objects, but offer more flexibility and functionality. However, when working with Maps, it's important to be aware of some common mistakes that developers can make. In this blog post, we will discuss these mistakes and show you how to avoid them.

Mistake 1: Using the wrong syntax to set values

One common mistake is to use the wrong syntax to set values in a Map. This can happen when developers try to set values using the same syntax as they would use for an object. For example:

const wrongMap = new Map();
wrongMap["key1"] = "Data1";
wrongMap["key2"] = "Data2";

This is incorrect because Maps are not meant to be accessed like objects. Instead, you should use the set() method to add key-value pairs to a Map:

const correctMap = new Map();
correctMap.set("key1", "Data1");
correctMap.set("key2", "Data2");

Mistake 2: Not using the has() method to check if a key exists

Another mistake that developers make is to assume that a key exists in a Map without checking for it first. This can result in errors or unexpected behavior. To avoid this, you should always use the has() method to check if a key exists before trying to access its value:

const myMap = new Map();
myMap.set("key1", "value1");

if (myMap.has("key1")) {
  console.log(myMap.get("key1"));
}

Mistake 3: Treating keys as strings when they are not

Maps can use any type of value as a key, not just strings. However, if you try to use a non-string value as a key, it will be converted to a string. This can lead to unexpected results if you are not aware of it. To avoid this, you should always use the same type of value for a key that you intend to use when you retrieve it later:

const myMap = new Map();
const objKey = {};
const arrKey = [];

myMap.set(objKey, "value1");
myMap.set(arrKey, "value2");

console.log(myMap.get(objKey)); // "value1"
console.log(myMap.get({})); // undefined
console.log(myMap.get(arrKey)); // "value2"
console.log(myMap.get([])); // undefined

In this example, we use an object and an array as keys. If we try to retrieve the values using a different object or array, we will get undefined. This is because the keys are not the same object or array, even though they may have the same content.

Best Practices

To use Maps effectively in your code, follow these best practices:

  • Always use the set() method to add key-value pairs.
  • Use the has() method to check if a key exists before trying to access its value.
  • Use the same type of value for a key that you intend to use when you retrieve it later.

By following these best practices, you can avoid common mistakes and use Maps effectively in your code.

Using NaN as a Key in JavaScript Maps

In JavaScript, NaN stands for "Not a Number" and is a special value that represents an unrepresentable or undefined value in a numeric context. One interesting feature of NaN is that it is not equal to any other value, including itself. This can make it a useful value to use as a key in Maps, but it also presents some challenges. In this blog post, we will explore how to use NaN as a key in Maps and some of the issues to be aware of.

Code Explanation

console.log(Number("Ram"));
const myMaps = new Map();
myMaps.set(NaN, "Not a Number");
console.log(myMaps.get(NaN));

The first line attempts to convert the string "Ram" into a number using the Number() function. Since "Ram" cannot be converted into a number, the result will be NaN.

Next, we create a new Map called myMaps and use the set() method to add a key-value pair to it. The key is NaN and the value is the string "Not a Number".

Finally, we use the get() method to retrieve the value associated with the key NaN from the map and log it to the console. The result will be "Not a Number".

Challenges of Using NaN as a Key

One of the main challenges of using NaN as a key in a Map is that NaN is not equal to any other value, including itself. This means that you cannot use the has() method to check if a key exists in a Map that is equal to NaN. Instead, you must use the isNaN() function to check for NaN explicitly:

const myMap = new Map();
myMap.set(NaN, "Not a Number");

console.log(myMap.has(NaN)); // false
console.log(isNaN([...myMap.keys()][0])); // true

In this example, we use the spread operator ... to convert the Map's keys into an array and then access the first key in the array. We then use the isNaN() function to check if this key is equal to NaN. The result will be true.

Another challenge of using NaN as a key is that it can cause unexpected behavior when used with certain operations, such as sorting:

const myMap = new Map();
myMap.set(NaN, "Not a Number");
myMap.set(1, "One");
myMap.set(2, "Two");

console.log([...myMap.entries()].sort()); // [[1, "One"], [2, "Two"], [NaN, "Not a Number"]]

In this example, we create a Map with three key-value pairs. When we use the spread operator and the sort() method to sort the entries, the NaN value will always be sorted to the end of the list. This is because NaN is not equal to any other value and cannot be compared using normal comparison operators.

Best Practices

To use NaN effectively as a key in your Map, follow these best practices:

  • Use isNaN() to check for NaN explicitly instead of using has().
  • Be aware of the potential for unexpected behavior when using NaN with certain operations, such as sorting.

By following these best practices, you can use NaN effectively as a key in your Maps without running into unexpected issues.

Merging Maps in JavaScript

In JavaScript, maps can be merged using the spread operator and an array. This allows you to combine the key-value pairs from multiple maps into a new map.

Here's an example of how to merge two maps using the spread operator:

//Maps can be merged with Arrays
const first = new Map([
  [1, "one"],
  [2, "two"],
  [3, "three"],
]);
const second = new Map([
  [1, "first"],
  [2, "second"],
]);
const merged = new Map([...first, ...second, [1, "Ist"]]);
console.log(merged);
console.log(merged.get(1));
console.log(merged.get(2));
console.log(merged.get(3));

This code demonstrates how two maps can be merged into a new map using the spread operator and an array.

In this example, we have two maps: first and second. first contains three key-value pairs, while second contains only two. We want to merge these maps into a new map called merged.

To do this, we create a new Map object and use the spread operator (...) to add the contents of both first and second maps to the new map. We also include an additional key-value pair [1, "Ist"] to overwrite the existing value for key 1 from first with the value "Ist". This means that the final value for key 1 in merged will be "Ist".

We then use the get() method to retrieve the values for each key in merged and log them to the console. The output will be:

Map(3) { 1 => 'Ist', 2 => 'second', 3 => 'three' }
Ist
second
three

Counting Word Frequency in JavaScript

we will explore how to count the frequency of words in a sentence using JavaScript.

Consider the following sentence:

Fear leads to anger anger leads to hatred hatred leads to conflict

Our goal is to count the frequency of each word in the sentence.

We can start by splitting the sentence into an array of words using the split() method. We pass a space " " as an argument to split the sentence into individual words:

const sentence = "Fear leads to anger anger leads to hatred hatred leads to conflict";
const words = sentence.split(" ");
console.log(words);

The output of console.log(words) will be an array of words:

[ 'Fear', 'leads', 'to', 'anger', 'anger', 'leads', 'to', 'hatred', 'hatred', 'leads', 'to', 'conflict' ]

Next, we create a Map() object to store the frequency of each word. We loop through each word in the words array and check if it already exists in the wordFrequency map using the has() method. If it exists, we increment the value of the corresponding key in the map using the get() and set() methods. If it does not exist, we set the value of the corresponding key to 1

const wordFrequency = new Map();
for (let word of words) {
  if (wordFrequency.has(word)) {
wordFrequency.set(word, wordFrequency.get(word) + 1);
  } else {
wordFrequency.set(word, 1);
  }
}
console.log(wordFrequency);

The output of console.log(wordFrequency) will be a Map() object containing the frequency of each word:

Map(6) {
  'Fear' => 1,
  'leads' => 3,
  'to' => 3,
  'anger' => 2,
  'hatred' => 2,
  'conflict' => 1
}

As we can see, the frequency of each word has been counted correctly. This technique can be useful for a variety of applications, such as analyzing text data or generating word clouds.

Grouping Objects by Property Value in JavaScript

we will explore how to group objects in an array by a specific property value using JavaScript.

Consider the following array of objects:

const people = [
{ name: "Raja", age: 30 },
{ name: "Sara", age: 25 },
{ name: "Suresh", age: 30 },
{ name: "Sundar", age: 25 },
];

Our goal is to group the objects in the array by age. In other words, we want to create a Map() object where each key is an age and the corresponding value is an array of objects with that age.

We can start by creating an empty Map() object to store the grouped objects:

const peopleByAge = new Map();

Next, we loop through each object in the people array and extract the age property. We check if the peopleByAge map already has a key with the same age using the has() method. If it exists, we get the value of the corresponding key using the get() method and push the current object into the array. If it does not exist, we create a new key-value pair where the key is the age and the value is an array containing the current object.

for (let person of people) {
  const age = person.age;
  if (peopleByAge.has(age)) {
peopleByAge.get(age).push(person);
  } else {
peopleByAge.set(age, [person]);
  }
}

Finally, we can log the peopleByAge map to see the result:

console.log(peopleByAge);

The output of console.log(peopleByAge) will be a Map() object containing the grouped objects:

Map(2) {
  30 => [    { name: 'Raja', age: 30 },    { name: 'Suresh', age: 30 }  ],
  25 => [    { name: 'Sara', age: 25 },    { name: 'Sundar', age: 25 }  ]
}

As we can see, the objects in the array have been grouped by age using the Map() object. This technique can be useful for a variety of applications, such as filtering or sorting data based on specific properties.

Counting the Frequency of Elements in an Array with JavaScript

In JavaScript, it is often useful to count the frequency of elements in an array. This can be achieved using a Map, which allows for efficient key-value pair storage and retrieval.

Here is an example function that counts the frequency of each element in an array:

function frequencyCounter(arr) {
  const map = new Map();
  for (let i = 0; i<arr.length; i++) {
    const element = arr[i];
map.set(element, (map.get(element) || 0) + 1);
  }
  return map;
}

The frequencyCounter function takes an array as input and returns a Map object with the frequency of each element. The function first initializes an empty Map object. It then iterates over the input array and sets each element as a key in the Map object. If the key already exists, the function increments the value of the key by 1. Otherwise, it sets the value of the key to 1.

Here are a couple of examples of using the frequencyCounter function:

const array = [1, 2, 3, 1, 2, 2, 4];
console.log(frequencyCounter(array));
// Output: Map(4) { 1 => 2, 2 => 3, 3 => 1, 4 => 1 }

const array2 = [1, 54, 1, 52];
console.log(frequencyCounter(array2));
// Output: Map(3) { 1 => 2, 54 => 1, 52 => 1 }

In the first example, the frequencyCounter function takes an array with 7 elements, and returns a Map object with 4 keys, each representing a unique element in the input array, and their corresponding values indicating the number of times the element appears in the input array.

In the second example, the frequencyCounter function takes an array with 4 elements, and returns a Map object with 3 keys, each representing a unique element in the input array, and their corresponding values indicating the number of times the element appears in the input array.

In summary, the frequencyCounter function is a useful utility function for counting the frequency of elements in an array using a Map object in JavaScript.

List of Programs


JS Practical Questions & Answers


JS Practical Project