Clean up messy data

“The data cleaner”, a Black belt challenge from the CurlyScript Dojo. It uses what Grade 13: Modern JavaScript Power-Ups teaches, and 3 tests check your answer.

The challenge

Write clean(records). Each record may have a name (with messy spaces) and an age that might be missing. Return new objects { name, age } where the name is trimmed (or "Unknown" if missing or blank) and a missing age becomes null. Keep an age of 0!

Example
clean([{ name: "  Mia " }, { age: 0 }])
// [{ name: "Mia", age: null }, { name: "Unknown", age: 0 }]

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • clean([{ name: " Mia ", age: 12 }]) gives [{ name: "Mia", age: 12 }]
  • clean([{ name: " Mia " }, { age: 0 }]) gives [{ name: "Mia", age: null }, { name: "Unknown", age: 0 }]
  • clean([{ name: " " }]) gives [{ name: "Unknown", age: null }]

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

record.name?.trim() won’t crash when the name is missing.

Hint 2

An empty string after trimming is falsy, so || "Unknown" handles blanks. But use ?? for the age, so 0 survives.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function clean(records) {
  return records.map((r) => ({
    name: r.name?.trim() || "Unknown",
    age: r.age ?? null,
  }));
}

Learn what you need

This exercise uses what Grade 13: Modern JavaScript Power-Ups teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning