The JavaScript map() method is a powerful tool for array manipulation. It iterates over each element of an array, applies a callback function to that element, and returns a new array containing the results. The original array remains unchanged, making it a key method for functional and immutable programming in JavaScript.
Example 1: Doubling Numbers in an Array
// Define an array of numbers
const numbers = [1, 2, 3, 4, 5];
// Use map to create a new array with each number doubled
const doubledNumbers = numbers.map(function(number) {
return number * 2;
});
// Log the new array to the console
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
Explanation:
This example demonstrates the basic usage of map(). It takes an array of numbers and creates a new array where each original number has been multiplied by 2.
Example 2: Converting Strings to Uppercase
// Define an array of strings
const words = ['hello', 'world', 'javascript'];
// Use map to create a new array with each word in uppercase
const uppercasedWords = words.map(word => word.toUpperCase());
// Log the new array to the console
console.log(uppercasedWords); // Output: ['HELLO', 'WORLD', 'JAVASCRIPT']
Explanation:
Here, map() is used with an array of strings. The arrow function word => word.toUpperCase() is a concise way to define the callback that converts each word to its uppercase equivalent.
Example 3: Extracting a Property from an Array of Objects
// Define an array of user objects
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
// Use map to create a new array containing only the names
const userNames = users.map(user => user.name);
// Log the new array to the console
console.log(userNames); // Output: ['Alice', 'Bob', 'Charlie']
Explanation:
This is a very common use case for map(). It efficiently extracts the value of a specific property (name) from each object in an array and collects them into a new array.
Example 4: Calculating the Square Root of Numbers
// Define an array of numbers
const values = [4, 9, 16, 25];
// Use map to create a new array with the square root of each number
const squareRoots = values.map(Math.sqrt);
// Log the new array to the console
console.log(squareRoots); // Output: [2, 3, 4, 5]
Explanation:
You can pass a pre-existing function, like Math.sqrt, directly to map(). The method will invoke this function for each element in the array, creating a new array of the results.
Example 5: Formatting Data into a New Object Structure
// Define an array of product data
const products = [
{ name: 'Laptop', price: 1200 },
{ name: 'Mouse', price: 25 },
{ name: 'Keyboard', price: 75 }
];
// Use map to reformat each product object
const formattedProducts = products.map(product => {
return {
productName: product.name,
productPrice: `$${product.price.toFixed(2)}`
};
});
// Log the new array of formatted objects
console.log(formattedProducts);
// Output:
// [
// { productName: 'Laptop', productPrice: '$1200.00' },
// { productName: 'Mouse', productPrice: '$25.00' },
// { productName: 'Keyboard', productPrice: '$75.00' }
// ]
Explanation:
This example showcases how map() can transform each element into a new object with a different structure. We are creating a new array of objects with different property names and formatted values.
Example 6: Using the Index in the Callback Function
// Define an array of items
const items = ['Apple', 'Banana', 'Cherry'];
// Use map to create a new array with the item and its index
const itemsWithIndex = items.map((item, index) => {
return `${index + 1}. ${item}`;
});
// Log the new array to the console
console.log(itemsWithIndex); // Output: ['1. Apple', '2. Banana', '3. Cherry']
Explanation:
The callback function for map() can also receive the index of the current element as a second argument. This is useful when the position of the element is important for the transformation.
Example 7: Parsing Strings into Integers
// Define an array of string numbers
const stringNumbers = ['10', '20', '30', '40'];
// Use map to parse each string into an integer
const parsedNumbers = stringNumbers.map(Number);
// Log the new array of numbers
console.log(parsedNumbers); // Output: [10, 20, 30, 40]
Explanation:
Similar to the Math.sqrt example, we can pass the Number constructor directly to map(). This provides a clean and readable way to convert an array of numeric strings into an array of actual numbers.