The map()
method creates a new array with the results of calling a function for every array element.
In this tutorial, you will learn how to use the JavaScript Array map()
method to transform elements in an array.
What is map() method in JavaScript?
The map()
method is used for array transformation. It takes another custom function as an argument and on each array item applies that function.
Example:
const numbers = [1, 2, 3, 4, 5]; // Use map() to double each number in the array const doubledNumbers = numbers.map((currentValue) => { return currentValue * 2; }); console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
In this example:
- We have an array called
numbers
containing integers. - We use the
map()
method to create a new array calleddoubledNumbers
. - Inside the
map()
function, we provide a callback that doubles each value in the original array.
map() Method Syntax
Arrow Function
map((currentValue) => { /* … */ }) map((currentValue, index) => { /* … */ }) map((currentValue, index, array) => { /* … */ })
Callback Function
map(callbackFn) map(callbackFn, thisValue)
Inline Callback Function
map(function (currentValue) { /* … */ }) map(function (currentValue, index) { /* … */ }) map(function (currentValue, index, array) { /* … */ }) map(function (currentValue, index, array) { /* … */ }, thisArg)
Parameters:
This method accepts two parameters as mentioned above and described below:
function(currentValue, index, array):
It is a required parameter and it runs on each element of the array. It contains three parameters which are listed below:
currentValue:
It is a required parameter and it holds the value of the current element.index
: It is an optional parameter and it holds the index of the current element.arr
ay: It is an optional parameter and it holds the array.
thisValue
: It is an optional parameter and is used to hold the value passed to the function.
Kindly remember, it returns a new array and elements of the arrays are the result of the callback function.
Practical Use Cases
The map()
method is incredibly useful in various scenarios, such as:
Transforming Data: You can use map()
to transform data from one format to another. For example, converting a list of objects into an array of their properties.
Rendering Lists in React: In React applications, map()
is often used to render lists of elements dynamically.
Data Manipulation: When you need to modify or manipulate data in an array without altering the original data, map()
is an excellent choice.
Generating New Arrays: If you want to create a new array based on an existing one, map()
is a concise way to do it.
The below examples illustrate the use of the array map()
method in JavaScript:
Example 1: How to Use map() Over an Array of Objects
For example, you may have an array of objects that stores firstName
and lastName
values of your friends as follows:
let users = [
{firstName : "Sunil", lastName: "Pradhan"},
{firstName : "Ram", lastName: "Sahu"},
{firstName : "Gopal", lastName: "Lal"}
];
You can use the map()
method to iterate over the array and join the values of firstName
and lastName
as follows:
let users = [ {firstName : "Sunil", lastName: "Pradhan"}, {firstName : "Ram", lastName: "Sahu"}, {firstName : "Gopal", lastName: "Lal"} ]; let userFullnames = users.map(function(element){ return `${element.firstName} ${element.lastName}`; }) console.log(userFullnames); // [ 'Sunil Pradhan', 'Ram Sahu', 'Gopal Lal' ]
Example 2
In below example map()
method takes in each city names from names array and returns new array with uppercase city names.
const names = ["bhubaneswar", "cuttack", "rourkela"]; const UpperCaseNames = names.map((name) => name.toLocaleUpperCase()); console.log(names); // [ 'bhubaneswar', 'cuttack', 'rourkela' ] console.log(UpperCaseNames); // [ 'BHUBANESWAR', 'CUTTACK', 'ROURKELA' ]
Example 3
In below example map()
method iterates over each employee data and returns netEarning for each employee in newArr.
const employees = [ { name: "Sunil", salary: 5000, bonus: 500, tax: 1000 }, { name: "Raj", salary: 8000, bonus: 1500, tax: 2500 }, { name: "Gopal", salary: 1500, bonus: 500, tax: 200 }, { name: "Hari", salary: 4500, bonus: 1000, tax: 900 }, ]; // calculate the net amount to be given to the employees const calcAmt = (obj) => { newObj = {}; newObj.name = obj.name; newObj.netEarning = obj.salary + obj.bonus - obj.tax; return newObj; }; let newArr = employees.map(calcAmt); console.log(newArr); /* Output will be : [ { name: 'Sunil', netEarning: 4500 }, { name: 'Raj', netEarning: 7000 }, { name: 'Gopal', netEarning: 1800 }, { name: 'Hari', netEarning: 4600 } ]*/
Example 4
The following example shows how to transform an array of numbers by using a built-in method of the Math
type as the callback function.
let numbers = [16, 25, 36]; let results = numbers.map(Math.sqrt); console.log(results); //[ 4, 5, 6 ]
The new array contains the square roots of the numbers in the numbers
array.
Example 5
Multiply all the values in an array with 10:
const numbers = [65, 44, 12, 4]; const newArr = numbers.map(myFunction) function myFunction(num) { return num * 10; } console.log(newArr); //[ 650, 440, 120, 40 ]
Example 6: With Index Value
This example uses the array map()
method and returns the square of the array element with index value.
// Input array let arr = [2, 5, 6, 3, 8, 9]; // Using map to transform elements let newArr = arr.map(function (val, index) { return { key: index, value: val * val }; }) // Display output console.log(newArr) /* Output will be : [ { key: 0, value: 4 }, { key: 1, value: 25 }, { key: 2, value: 36 }, { key: 3, value: 9 }, { key: 4, value: 64 }, { key: 5, value: 81 } ] */
Example 7: Using map() to Extract Specific Information
In the given array of products:
const products = [ { id: 1, name: 'item 1', price: 29.99, description: "Product 1", category: "Electronics" }, { id: 2, name: 'item 2', price: 19.95, description: "Product 2", category: "Clothing" }, { id: 3, name: 'item 3', price: 49.99, description: "Product 3", category: "Home Decor" }, { id: 4, name: 'item 4', price: 9.99, description: "Product 4", category: "Kitchen" } ];
You might want to extract specific information, such as the names of the products or their prices. This is where the map()
method shines.
Extracting Product Names
Suppose you want to create an array containing only the names of the products. You can use the map()
method to achieve this:
const products = [ { id: 1, name: 'item 1', price: 29.99, description: "Product 1", category: "Electronics" }, { id: 2, name: 'item 2', price: 19.95, description: "Product 2", category: "Clothing" }, { id: 3, name: 'item 3', price: 49.99, description: "Product 3", category: "Home Decor" }, { id: 4, name: 'item 4', price: 9.99, description: "Product 4", category: "Kitchen" } ]; const productNames = products.map((product) => { return product.name; }); console.log(productNames); //[ 'item 1', 'item 2', 'item 3', 'item 4' ]
In this case:
- We apply the
map()
method to theproducts
array. - The callback function extracts the
name
property from each product and returns it. - The resulting
productNames
array will contain the names of all the products.
Extracting Product Prices
Similarly, if you want to create an array containing only the prices of the products:
const products = [ { id: 1, name: 'item 1', price: 29.99, description: "Product 1", category: "Electronics" }, { id: 2, name: 'item 2', price: 19.95, description: "Product 2", category: "Clothing" }, { id: 3, name: 'item 3', price: 49.99, description: "Product 3", category: "Home Decor" }, { id: 4, name: 'item 4', price: 9.99, description: "Product 4", category: "Kitchen" } ]; const productPrices = products.map((product) => { return product.price; }); console.log(productPrices); //[ 29.99, 19.95, 49.99, 9.99 ]
In this case:
- We use the
map()
method again. - The callback function extracts the
price
property from each product and returns it. - The resulting
productPrices
array will contain the prices of all the products.
Conclusion
In this tutorial, you have learned how to use the JavaScript map()
method to transform elements of an array according to a provided function.
In summary, the map()
method is a fundamental tool in JavaScript for iterating over arrays and applying a function to each element to create a new array with modified elements.
Thanks for reading this post.
Add comment