❀ Like
πŸ”– Save
πŸ”— Share
@thedevspaceio
@thedevspaceio

JavaScript Array map() Cheatsheet

@thedevspaceio

πŸ—ΊοΈ JavaScript Array map() Cheatsheet

map() transforms every element in an array and returns a new array, making it essential for data transformation.

βœ… Basic syntax βœ… Transforming values βœ… Mapping objects βœ… Using index and array βœ… Chaining with other methods

#javascript #arrays #map #transform #functional #webdev #frontend #coding #tips


map() calls a function on every element in an array, and returns a new array with the results.

It does not mutate the original array.

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

Basic syntax

js
array.map((element, index, array) => {
  // return new value
});
ParameterDescription
elementThe current element being processed.
indexThe index of the current element.
arrayThe original array map was called on.

Transforming values

Double every number.

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

Convert strings to uppercase.

js
const names = ["ada", "grace", "alan"];
const upper = names.map((name) => name.toUpperCase());
 
console.log(upper); // ["ADA", "GRACE", "ALAN"]

Mapping objects

Extract a property from each object.

js
const users = [
  { name: "Ada", role: "admin" },
  { name: "Grace", role: "editor" },
];
 
const names = users.map((user) => user.name);
console.log(names); // ["Ada", "Grace"]

Transform objects into a new shape.

js
const products = [
  { name: "Laptop", price: 1000 },
  { name: "Mouse", price: 50 },
];
 
const labels = products.map((p) => ({
  label: `${p.name}: $${p.price}`,
}));
 
console.log(labels);
// [{ label: "Laptop: $1000" }, { label: "Mouse: $50" }]

Using index and array

Use the index to generate values.

js
const items = ["a", "b", "c"];
const numbered = items.map((item, index) => `${index + 1}. ${item}`);
 
console.log(numbered); // ["1. a", "2. b", "3. c"]

Use the original array for relative calculations.

js
const scores = [10, 20, 30];
const percentages = scores.map(
  (score, _, arr) => score / arr.reduce((a, b) => a + b, 0),
);
 
console.log(percentages); // [0.167, 0.333, 0.5]

Chaining with other methods

map() works well with filter() and reduce().

js
const users = [
  { name: "Ada", age: 25, active: true },
  { name: "Grace", age: 30, active: false },
  { name: "Alan", age: 35, active: true },
];
 
const activeNames = users.filter((u) => u.active).map((u) => u.name);
 
console.log(activeNames); // ["Ada", "Alan"]

Full-Stack AI Developer Roadmap

From HTML & CSS to working with AI models, all in one structured roadmap.

@thedevspaceio
www.thedevspace.io