In JavaScript, the map() method is used to create a new array by calling a function on every element in an existing array. It doesn’t modify the original array; instead, it returns a new array with the transformed elements.
Syntax
const newArray = originalArray.map(callbackFunction);
originalArray: The array you want to transform.callbackFunction: The function to apply to each element, which receives up to three arguments:currentValue: The current element being processed in the array.index(optional): The index of the current element.array(optional): The array thatmap()is called upon.
Example 1: Basic map() Usage
Let’s create an array of numbers and use map() to create a new array with each number doubled.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8]
Example 2: Using map() with an Object Array
If you have an array of objects, you can use map() to extract a specific property from each object.
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
];
const names = users.map(user => user.name);
console.log(names); // Output: ["Alice", "Bob", "Charlie"]
Example 3: Using map() with Index
You can also use the index of each element in your transformation.
const numbers = [10, 20, 30];
const indexedNumbers = numbers.map((num, index) => num + index);
console.log(indexedNumbers); // Output: [10, 21, 32]
Example 4: Chaining map() with Other Array Methods
You can chain map() with other array methods, like filter() or reduce(), for more complex transformations.
const numbers = [1, 2, 3, 4, 5];
const doubledEven = numbers
.filter(num => num % 2 === 0) // Filter even numbers
.map(num => num * 2); // Double each even number
console.log(doubledEven); // Output: [4, 8]
Summary
The map() method is versatile and useful for transforming arrays without mutating the original data, allowing for more readable and functional code.


Leave a Reply