Array.map()
The Array.map()
method in JavaScript is used to create a new array by applying a callback function to each element of the calling array. It does not mutate the original array but returns a new one.
Syntax
array.map(callbackFn)
array.map(callbackFn, thisArg)
Parameters
Parameter | Description |
---|---|
callbackFn | A function to execute on each element in the array. It takes up to three arguments: currentValue (the current element being processed), index (the index of the current element), and array (the array being processed). |
thisArg (optional) | Value to use as this when executing callbackFn . |
Return Value
The map()
method returns a new array where each element is the result of applying the callbackFn
to the corresponding element in the original array.
Examples
1. Basic Usage
In this example, each element of the array is doubled using the map()
method.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled);
Output
[2, 4, 6, 8]
callbackFn
multiplies each element of thenumbers
array by 2.- The method returns a new array containing the doubled values.
2. Using index
in the Callback Function
You can access the index of each element inside the callbackFn
.
const numbers = [10, 20, 30];
const result = numbers.map((num, index) => num + index);
console.log(result);
Output
[10, 21, 32]
Here, the value of each element is incremented by its index in the array.
3. Using thisArg
Parameter
The thisArg
parameter allows you to provide a custom context for the callbackFn
.
const multiplier = {
factor: 3,
};
const numbers = [1, 2, 3];
const tripled = numbers.map(function (num) {
return num * this.factor;
}, multiplier);
console.log(tripled);
Output
[3, 6, 9]
The thisArg
ensures that this.factor
refers to the factor
property of the multiplier
object.
4. Mapping an Array of Objects
The map()
method is often used to extract or transform properties from an array of objects.
const users = [
{ name: "Akash", age: 25 },
{ name: "Bhairav", age: 30 },
{ name: "Charlie", age: 35 },
];
const names = users.map(user => user.name);
console.log(names);
Output
[ 'Akash', 'Bhairav', 'Charlie' ]
Here, user.name
is extracted from each object in the array.
5. Chaining map()
with Other Methods
The map()
method is commonly chained with other array methods for complex transformations.
const numbers = [1, 2, 3, 4, 5];
const result = numbers
.map(num => num * 2)
.filter(num => num > 5);
console.log(result);
Output
[6, 8, 10]
In this example, the array is first doubled using map()
and then filtered to include only numbers greater than 5.