map
Transform every item. Same length, new array.
map runs your function once per item and hands back a new array of the results: same length, same order, input untouched.
Reach for it whenever you have a list of one shape and want a list of another shape: pick a field, add a field, compute something per item, format for display.
Shape
const out = items.map((item, index) => newValue); Patterns
-
docs.map((d) => d.title)Pick one field.
-
users.map((u) => ({ ...u, active: true }))Add or change a field without mutating. The parentheses around the braces matter: without them the braces are a function body and you return undefined.
-
questions.map((q, i) => (i + 1) + ". " + q.prompt)Use the index.
-
results.map((r) => Math.round((100 * r.correct) / r.total))Compute something per item.
Pitfalls
- Forgetting
returnin a block body gives you an array ofundefined. mapis for producing a new array. If you only want side effects, useforEachor a plain loop.["1", "2", "3"].map(parseInt)returns[1, NaN, NaN], becausemappasses the index as the second argument andparseIntreads it as a radix. Wrap it or useNumber.
Exercises
Write the function, run it against the hidden cases. Cmd or Ctrl + Enter runs, Tab indents, Esc then Tab leaves the editor. 0 / 5 solved.
1. Titles
Given a list of documents, return their titles in the same order.
titles([{ id: 1, title: "Q3 notes" }, { id: 2, title: "Onboarding" }]) → ["Q3 notes", "Onboarding"] 2. Percentages
Each result has correct and total. Return a list of integer percents, one per result, rounded to the nearest integer. A total of 0 gives 0.
percentages(
[
{ correct: 3, total: 4 },
{ correct: 1, total: 3 },
{ correct: 0, total: 0 }
]
) → [75, 33, 0] 3. Mark passed
Return a new list of students with a passed field, true when score >= passMark. Keep every existing field. Do not mutate the input.
markPassed([{ name: "Ana", score: 80 }, { name: "Bo", score: 60 }], 70) → [
{ name: "Ana", score: 80, passed: true },
{ name: "Bo", score: 60, passed: false }
] 4. Numbered prompts
Each question has a prompt. Return one string per question in the form 1. What is a vital sign?: the position starting at 1, a period and a space, then the prompt.
numberedPrompts(
[
{ prompt: "What is a vital sign?" },
{ prompt: "Normal pulse?" }
]
) → ["1. What is a vital sign?", "2. Normal pulse?"] 5. Initials
Given full names, return the initials in uppercase: "rafael segarra" becomes "RS". Names may have any number of words and extra spaces around or between them.
initials(["rafael segarra", "Ana Maria Lopez"])
→ ["RS", "AML"] Keep the items that pass a test. Same items, fewer of them.