The JavaScript map()
method is used to iterate over an array and transform its elements based on a given callback function. It creates a new array with the results of calling the callback function on each element of the original array. The map()
method does not modify the original array; instead, it returns a new array with the transformed elements in the same order.
array.map(callback(currentValue, index, array), thisArg)
array
: The original array to be iterated over.callback
: The function to be called for each element in the array. It accepts three arguments: currentValue
(the current element being processed), index
(the index of the current element), and array
(the array being traversed).thisArg
(optional): The value to be used as this
when executing the callback function.map()
is commonly used to transform each element of an array into a new value or format. For example, you can convert an array of numbers to an array of their squares:const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // [1, 4, 9, 16, 25]
map()
can be used to transform an array of objects by modifying or extracting specific properties 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); // ['Alice', 'Bob', 'Charlie']
map()
is useful for formatting data in a specific structure.const strings = ['apple', 'banana', 'orange'];
const htmlElements = strings.map(str => `${str} `);
console.log(htmlElements);
// ['apple ', 'banana ', 'orange ']
map()
can be combined with other methods to filter elements based on certain conditions.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.map(num => num * 2).filter(num => num % 2 === 0);
console.log(evenNumbers)
map()
method provides the index as the second argument to the callback function. Here's an example where we prepend the index to each element in the array:const fruits = ['apple', 'banana', 'orange'];
const indexedFruits = fruits.map((fruit, index) => `${index + 1}. ${fruit}`);
console.log(indexedFruits);
// ['1. apple', '2. banana', '3. orange']
These are just a few examples of how the map()
method can be used. It is a versatile method that allows you to transform and manipulate arrays in various ways based on your requirements.