Back to the blog

Tony CantaveCleaning a Messy List in JavaScript with map, filter and reduce

By Tony Cantave ·

Some of the JavaScript I write for AI evaluation work is small data cleaning code: take a list that came from a form or a spreadsheet, fix it up, and return something a person can trust. It is also the kind of code I write for my own projects, like the screen management software I am building. The tools are almost always the same: map, filter, reduce and a Set. Here is how I use them on a realistic messy list.

The starting data

const signups = [
  { name: "  Maria Lopez ", email: "Maria@Example.com ", town: "new haven" },
  { name: "James Carter", email: "jcarter@example.com", town: "Bridgeport" },
  { name: "", email: "", town: "" },
  { name: "maria lopez", email: "maria@example.com", town: "New Haven" },
  { name: "Ana Silva", email: "ana.silva@example", town: "Hamden " },
];

Five rows, and almost every one has a problem: extra spaces, mixed case, an empty row, a duplicate that only looks different because of formatting, and an email address with no domain ending.

Step 1: normalize every row with map

map takes each item and returns a new item. It never changes the original array, which matters when you want to compare before and after.

const titleCase = (text) =>
  text
    .toLowerCase()
    .split(" ")
    .filter(Boolean)
    .map((word) => word[0].toUpperCase() + word.slice(1))
    .join(" ");

const normalized = signups.map((row) => ({
  name: titleCase(row.name.trim()),
  email: row.email.trim().toLowerCase(),
  town: titleCase(row.town.trim()),
}));

The filter(Boolean) inside titleCase quietly removes the empty strings you get when someone types two spaces between words.

I always normalize first and validate second. If you validate first, an address like " Maria@Example.com " can fail a check for reasons that have nothing to do with whether it is real.

Step 2: drop rows that cannot be used, with filter

const looksLikeEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

const usable = normalized.filter(
  (row) => row.name && looksLikeEmail(row.email)
);

This regular expression is a shape check, not proof that an inbox exists. It catches the empty row and the address with no ending after the domain, which is all I need at this stage.

Just as important, I keep the rows I threw away:

const rejected = normalized.filter((row) => !usable.includes(row));
console.log(`Rejected ${rejected.length} rows`, rejected);

Silently dropping rows is the bug I see most often in small samples. A script that throws data away without a word looks fine until someone asks where their signup went.

Step 3: remove duplicates with a Set

const seen = new Set();
const unique = usable.filter((row) => {
  if (seen.has(row.email)) return false;
  seen.add(row.email);
  return true;
});

The key here is the cleaned email address. This is the payoff from normalizing first: "Maria@Example.com " and "maria@example.com" are the same person once both are trimmed and lowercased. This version keeps the first row it sees, so if your data has a "most recent wins" rule, sort by date before this step.

Step 4: summarize with reduce

const countsByTown = unique.reduce((counts, row) => {
  counts[row.town] = (counts[row.town] || 0) + 1;
  return counts;
}, {});

console.log(countsByTown);
// { "New Haven": 1, Bridgeport: 1 }

Always pass the starting value, the {} at the end. Without it, reduce uses the first row as the accumulator, and on an empty array it throws a TypeError. That second case will not show up in your test data, but it will show up the first day the form gets no signups.

Step 5: check the result with plain asserts

Node ships with an assert module, so there is nothing to install.

const assert = require("node:assert");

assert.strictEqual(unique.length, 2);
assert.strictEqual(rejected.length, 2);
assert.deepStrictEqual(countsByTown, { "New Haven": 1, Bridgeport: 1 });

Two usable people, two rejected rows, and the counts by town match what I expect from reading the data by hand. If any of those numbers surprise me, I stop and find out why before going further.

Mistakes I watch for

  1. Changing the original object inside map, such as writing row.name = something. Then any before and after comparison lies to you.
  2. Using map when nothing is returned. If you only want a side effect like logging, forEach says that more honestly.
  3. Chaining so many calls into one expression that nobody can debug it. Named steps like normalized, usable and unique make each stage easy to print.
  4. Forgetting the starting value in reduce.
  5. Comparing or deduplicating before normalizing.

Why I work this way

Before software I spent years in manufacturing and logistics operations. The rule on a production line was to fix a problem at the station where it starts, not at final inspection, because by then it has been copied into everything downstream. Data cleaning works the same way. Normalize at the start, keep what you reject, count what you keep, and check the numbers before anything leaves your hands.

If you have a small cleaning script that has been "working fine," try adding a rejected list and three asserts. It is a cheap way to find out whether it really is.