javascript drills

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

Pitfalls

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.

Example
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.

Example
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.

Example
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.

Example
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.

Example
initials(["rafael segarra", "Ana Maria Lopez"])
→ ["RS", "AML"]
Next lesson filter

Keep the items that pass a test. Same items, fewer of them.