Skip to main content

map() Method

The map(callback) method is used to transform an array. It calls a callback for each element of the original array and writes its result to a new array, which will be the method execution result.

array.map((element, index, array) => {
// Callback body
});
  • Iterates over the original array element by element.
  • Does not change the original array.
  • The callback function’s result is written to a new array.
  • Returns a new array of the same length.

It can be used to change every element of an array. The original array is used as a reference, a basis for making another collection.

const planets = ["Earth", "Mars", "Venus", "Jupiter"];

const planetsInUpperCase = planets.map(planet => planet.toUpperCase());
console.log(planetsInUpperCase); // ['EARTH', 'MARS', 'VENUS', 'JUPITER']

const planetsInLowerCase = planets.map(planet => planet.toLowerCase());
console.log(planetsInLowerCase); // ['earth', 'mars', 'venus', 'jupiter']

// The original array has not changed
console.log(planets); // ['Earth', 'Mars', 'Venus', 'Jupiter']

Using anonymous arrow functions with an implicit return greatly reduces the "noise" when declaring a callback function, making the code cleaner and easier to read.

Array of objects

You already know that a programmer’s daily task is to manipulate arrays of objects. For example, to get an array of property values from all objects. Imagine that you have an array of students and need to get a separate array of their names.

const students = [
{ name: "Mango", score: 83 },
{ name: "Poly", score: 59 },
{ name: "Ajax", score: 37 },
{ name: "Kiwi", score: 94 },
{ name: "Houston", score: 64 },
];

const names = students.map(student => student.name);
console.log(names); // ['Mango', 'Poly', 'Ajax', 'Kiwi', 'Houston']

Using the map() method, you can iterate over an array of objects and return the property value of each of them in a callback.