Transforming Arrays with map

The map method creates a new array by applying a function to each element of the original array. It is the most common way to transform data declaratively.

Basic Usage

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((n) => n * 2);
console.log(doubled);  // [2, 4, 6, 8, 10]

The original array remains unchanged:

console.log(numbers);  // [1, 2, 3, 4, 5]

Extracting Properties

We often use map to pull specific properties out of objects:

const users = [
  { id: 1, name: "Alice", email: "alice@example.com" },
  { id: 2, name: "Bob", email: "bob@example.com" },
  { id: 3, name: "Charlie", email: "charlie@example.com" },
];

const names = users.map((user) => user.name);
console.log(names);  // ['Alice', 'Bob', 'Charlie']

const emails = users.map((user) => user.email);
console.log(emails);  // ['alice@example.com', 'bob@example.com', 'charlie@example.com']

Transforming Object Shapes

You can reshape objects by returning new objects from the callback:

const users = [
  { firstName: "Alice", lastName: "Smith", age: 28 },
  { firstName: "Bob", lastName: "Jones", age: 34 },
];

const formatted = users.map((user) => ({
  fullName: `${user.firstName} ${user.lastName}`,
  isAdult: user.age >= 18,
}));

console.log(formatted);
// [
//   { fullName: 'Alice Smith', isAdult: true },
//   { fullName: 'Bob Jones', isAdult: true }
// ]

Using the Index Parameter

The callback function receives the current index as its second argument:

const letters = ["a", "b", "c"];
const indexed = letters.map((letter, index) => `${index}: ${letter}`);
console.log(indexed);  // ['0: a', '1: b', '2: c']

Chaining with Other Methods

Since map returns an array, you can chain it with other array methods:

const products = [
  { name: "Laptop", price: 999 },
  { name: "Phone", price: 699 },
  { name: "Tablet", price: 449 },
];

const discountedPrices = products
  .map((p) => p.price)
  .map((price) => price * 0.9);

console.log(discountedPrices);  // [899.1, 629.1, 404.1]