How to use .map() to iterate through array items
map() creates a new array by transforming every element in the original. It is one of the most commonly used array methods in JavaScript.
I. What is map()?
map() runs a callback function on each element and collects the return values into a new array. The original array is not changed. The new array is always the same length as the original.
II. Syntax
const newArray = array.map((currentElement, index, array) => {
return /* transformed value */;
});
currentElement: the current item being processed.index: the position of the current item (optional).array: the original array (optional).
III. Basic example
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]
console.log(numbers); // [1, 2, 3, 4] (unchanged)
IV. For loop vs map()
These two examples produce the same result, but map() is shorter and expresses intent more clearly:
// Using a for loop
const arr = [1, 2, 3, 4];
const plus5 = [];
for (let i = 0; i < arr.length; i++) {
plus5[i] = arr[i] + 5;
}
console.log(plus5); // [6, 7, 8, 9]
// Using map()
const arr = [1, 2, 3, 4];
const plus5 = arr.map(val => val + 5);
console.log(plus5); // [6, 7, 8, 9]
V. Using map() with an array of objects
A common use case is pulling specific values from a list of objects:
const people = [
{ firstName: 'Anna', lastName: 'Smith' },
{ firstName: 'John', lastName: 'Doe' },
{ firstName: 'Peter', lastName: 'George' },
];
const fullNames = people.map(person => `${person.firstName} ${person.lastName}`);
console.log(fullNames);
// ['Anna Smith', 'John Doe', 'Peter George']
VI. Using the index
The second argument in the callback is the index:
const names = ['Anna', 'John', 'Peter'];
names.map((name, index) => console.log(`${index}: ${name}`));
// 0: Anna
// 1: John
// 2: Peter
VII. Constructing a new shape
You can use map() to reshape each object in an array:
const people = [
{ name: 'Anna', age: 35, position: 'Designer' },
{ name: 'John', age: 20, position: 'Developer' },
{ name: 'Peter', age: 26, position: 'CEO' },
];
const summary = people.map(person => ({
firstName: person.name.toUpperCase(),
seniority: person.age >= 30 ? 'senior' : 'junior',
}));
console.log(summary);
// [
// { firstName: 'ANNA', seniority: 'senior' },
// { firstName: 'JOHN', seniority: 'junior' },
// { firstName: 'PETER', seniority: 'junior' },
// ]
Keep in mind
map() always returns a new array of the same length as the original. If you want to return only some elements, use filter()
. If you want to combine all elements into a single value, use reduce()
.