Applications of Map in JavaScript
Last Updated :
11 Jul, 2023
Javascript Map is a collection of elements where each element is stored as a Key, value pair. Map objects can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, and value pair in the same order as inserted.
Syntax:
new Map([it]);
Parameter:
- it: It is any iterable object whose values are stored as key, value pair, If the parameter is not specified then a new map is created
is Empty.
Return Value: A new Map object.
Applications of Map:
1. Array Manipulation: A map can also be used to change or transform an array's elements according to condition. As an illustration, you might use the map to double each integer in an array of numbers.
Example: In this example, we are doubling the element of an array by using the map.
JavaScript
let array = [10, 20, 30, 40, 50, 60];
let newArray = array.map((num) => {
return num * 2;
});
console.log(newArray);
Output:
(6) [20, 40, 60, 80, 100, 120]
2. Filtering data: The map() method can be used to filter data by returning a new array with only the elements that pass a certain condition. This can be achieved by returning undefined elements that do not pass the condition.
Example: here we will use map() to filter even odd numbers from our array.
JavaScript
let array = [1, 2, 3, 4, 5, 6];
function solution(array) {
let result = "";
array.map((item) => {
if (item % 2 === 0) {
result += "even "
} else {
result += "odd "
}
})
return result
}
console.log(solution(array));
Output:
"odd even odd even odd even "
3. Converting data types: The map() method can be used to convert data types by applying a function that returns a new value with a different data type. This is useful when working with APIs that return data in a format that needs to be converted to another format.
Example: Here with the help of map() we can convert our string into an array.
JavaScript
const language = "GeeksforGeeks";
const map = Array.prototype.map;
const letters = map.call(language, (eachLetter) => {
return `${eachLetter}`;
});
console.log(letters);
Output:
["G", "e", "e", "k", "s", "f", "o", "r", "G", "e", "e", "k", "s"]
4. Caching and Memoization: A map can be used to implement a cache for expensive function results or computed data. we can optimize efficiency by avoiding redundant computations by using function arguments as keys and associated outcomes as values. When dealing with computationally demanding operations or regularly accessed data that can be stored.
Example: Here is an example of the above-explained method.
JavaScript
// Caching and Memoization using Map
// Create a Map for caching computed values
const cache = new Map();
// Example function to demonstrate
// expensive computation
function myValue(n) {
console.log(`value for ${n}...`);
const result = n * Math.random();
return result;
}
// Function to get a cached value or
// compute and cache if not present
function getCachedValue(n) {
if (cache.has(n)) {
console.log(`Fetching cached value for ${n}...`);
return cache.get(n);
} else {
const result = myValue(n);
cache.set(n, result);
return result;
}
}
// Compute and cache for key 2
console.log(getCachedValue(2));
// Retrieve from cache for key 2
console.log(getCachedValue(2));
// Compute and cache for key 5
console.log(getCachedValue(5));
// Retrieve from cache for key 5
console.log(getCachedValue(5));
// Retrieve from cache for key 2
// (already computed)
console.log(getCachedValue(2));
Output:
value for 2...
1.7458614577470124
Fetching cached value for 2...
1.7458614577470124
value for 5...
2.590270481082264
Fetching cached value for 5...
2.590270481082264
Fetching cached value for 2...
1.7458614577470124
5. URL Routing: Map can be used in web applications to map URL pathways to appropriate handlers or methods. The handler function or related metadata may be the associated value with the key being the URL path. This strategy makes it possible for the application to route and navigate users effectively.
Example: Here is an example of the above method.
JavaScript
// Create a Map for URL routing
const routes = new Map();
// Function to handle home page
function myGfg() {
console.log("Welcome to the GeeksforGeeks");
}
// Function to handle about page
function myPortal() {
console.log("A Computer secience protal.");
}
// Function to handle contact page
function myContact() {
console.log("You've reached the contact page.");
}
// Function to handle 404 (page not found) error
function notFoundHandler() {
console.log("404 - Page not found");
}
// Configure the routes
routes.set("/", myGfg);
routes.set("/about", myPortal);
routes.set("/contact", myContact);
// Function to handle incoming requests
function handleRequest(url) {
if (routes.has(url)) {
const handler = routes.get(url);
handler();
} else {
notFoundHandler();
}
}
// Simulating incoming requests
handleRequest("/"); // Home page
handleRequest("/about"); // About page
handleRequest("/contact"); // Contact page
handleRequest("/products"); // Page not found
Output:
Welcome to the GeeksforGeeks
A Computer secience protal.
You've reached the contact page.
404 - Page not found
Here are some methods of the map in JavaScript
Please refer to the Javascript Map Complete reference article for a detailed description of the Map.
Similar Reads
Map to Array in JavaScript In this article, we will convert a Map object to an Array in JavaScript. A Map is a collection of key-value pairs linked with each other. The following are the approaches to Map to Array conversion: Methods to convert Map to ArrayUsing Spread Operator (...) and Array map() MethodUsing Array.from() M
3 min read
How to Sort a Map in JavaScript? Sorting a Map in JavaScript involves ordering its key-value pairs based on the keys or values. Since Maps maintain the insertion order, you can't directly sort them like arrays. Instead, you'll need to convert the Map into an array, sort it, and then convert it back into a Map.Below are the approach
3 min read
How to create an image map in JavaScript ? An image map is nothing but an image that is broken into various hotspots and each hotspot will take you to a different file. Hotspots are nothing but clickable areas which we create on an image by using the <area> tag. This type of map is called a client-side image map as the map is embedded
3 min read
How to sort a collection in JavaScript ? A javascript collection is much like a container. It's just an item that combines several elements into a single unit. Aggregate information is stored, accessed, modified, and communicated via collections. With the help of constructors, we create collections in javascript. In earlier versions of jav
3 min read
JavaScript Index inside map() Function In JavaScript, the map() functionâs callback provides an optional second parameter, the index, representing the current element's position in the array. This index starts at 0 and increments for each element, allowing access to each itemâs position during iteration.Syntax:array.map(function(currente
3 min read