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
const cache = new Map();
function myValue(n) {
console.log(`value for ${n}...`);
const result = n * Math.random();
return result;
}
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;
}
}
console.log(getCachedValue(2));
console.log(getCachedValue(2));
console.log(getCachedValue(5));
console.log(getCachedValue(5));
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
const routes = new Map();
function myGfg() {
console.log( "Welcome to the GeeksforGeeks" );
}
function myPortal() {
console.log( "A Computer secience protal." );
}
function myContact() {
console.log( "You've reached the contact page." );
}
function notFoundHandler() {
console.log( "404 - Page not found" );
}
routes.set( "/" , myGfg);
routes.set( "/about" , myPortal);
routes.set( "/contact" , myContact);
function handleRequest(url) {
if (routes.has(url)) {
const handler = routes.get(url);
handler();
} else {
notFoundHandler();
}
}
handleRequest( "/" );
handleRequest( "/about" );
handleRequest( "/contact" );
handleRequest( "/products" );
|
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 approac
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(curren
3 min read
Chaining of Array Methods in JavaScript
There are some methods in JavaScript that can loop through the array. We already have a knowledge about these array methods. Filter method ( filter()) Map method ( map()) Reduce method ( reduce()) Find method ( find()) Sort method ( sort()) We will learn how to chain all the array methods together.
3 min read
Internal Working of Map in JavaScript
The 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. In this article, we will check the internal working of a Map in JavaScript. Internal Working of Map The Map in JavaScript allows for s
3 min read
JavaScript Map has() Method
The has() method in JavaScript Map returns a boolean indicating whether a specified element is present in the Map object or not. It returns true if the element is found, otherwise false. Syntax:mapObj.has(key)Parameters:key: It is the key of the element of the map which has to be searched.Return Val
3 min read
Map() vs Filter() Methods in JavaScript
In JavaScript, the map() and filter() methods are powerful array functions that allow you to transform and filter arrays easily. We will discuss the required concepts about each method in this article. What is map() in JavaScript?The map() method creates a new array by applying a given function to e
3 min read
JavaScript Map entries() Method
JavaScript Map.entries() method is used for returning an iterator object which contains all the [key, value] pairs of each element of the map. It returns the [key, value] pairs of all the elements of a map in the order of their insertion. The Map.entries() method does not require any argument to be
4 min read