Problem Statement
What does the map method do?
Explanation
The map method creates a new array by applying a function to each element of the original array.
It returns a new array with the same length as the original. The original array remains unchanged.
Map is used for transforming data, like extracting properties, formatting values, or performing calculations.
The callback function receives the current element, index, and the whole array.
Map is one of the most important array methods in functional programming.
Code Solution
SolutionRead Only
const numbers = [1, 2, 3, 4, 5];
// Transform each element
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5] (unchanged)
// Extract property from objects
const users = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 35 }
];
const names = users.map(user => user.name);
console.log(names); // ['John', 'Jane', 'Bob']
// Using index
const indexed = numbers.map((num, index) => num * index);
console.log(indexed); // [0, 2, 6, 12, 20]
// Convert to strings
const strings = numbers.map(num => String(num));
console.log(strings); // ['1', '2', '3', '4', '5']
// Complex transformation
const formatted = users.map(user => ({
fullName: user.name.toUpperCase(),
isAdult: user.age >= 18
}));