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 = "neveropen" ; 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 neveropen" ); } // 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 neveropen A Computer secience protal. You've reached the contact page. 404 - Page not found
Here are some methods of the map in JavaScript
- JavaScript Map clear() Method: Removal of all the elements from a map and making it empty.
- JavaScript Map delete() Method: Delete the specified element among all the elements which are present in the map.
- JavaScript Map entries() Method: Returning an iterator object which contains all the [key, value] pairs of each element of the map.
- JavaScript Map forEach() Method: The map with the given function executes the given function over each key-value pair.
- JavaScript Map get() Method: Returning a specific element among all the elements which are present in a map.
- JavaScript Map has() Method: Check whether an element with a specified key exists in a map or not.
- JavaScript Map keys() Method: The keys from a given map object return the iterator object of keys.
- JavaScript Map set() Method: Add key-value pairs to a Map object.
- JavaScript Map values() Method: Return a new Iterator object that contains the value of each element present in Map.
Please refer to the Javascript Map Complete reference article for a detailed description of the Map.