StoicBuilder

HandbookI the LudusMap, filter and reduce

Ithe Ludus, Read code

Map, filter and reduce

1 min readUpdated 28 November

In plain words

These three methods work through a list: map turns each item into something new, filter keeps the ones that pass a test, and reduce combines them into one value.

Where you see it

Almost every list on screen in a React app goes through .map(): Chirp's feed takes posts and maps each one to a card. A "show only my posts" toggle is a filter, and a cart total is often a reduce.

src/lib/cart.tsbrowser
const names = items.map((item) => item.name);const available = items.filter((item) => item.inStock);const total = items.reduce( (sum, item) => sum + item.price * item.quantity, 0);
Each returns something new. The original items list is untouched.

What goes wrong

  1. Curly braces with no return

    With braces, an arrow function needs the word return. Without it, map builds a list of undefined.

    items.map((item) => { item.name })
  2. Leaving out reduce's starting value

    Without the 0 at the end, reduce starts from the first item itself. On an empty cart it throws "Reduce of empty array with no initial value".

  3. No key on list items

    When map builds a list of components, each needs a stable key such as post.id. Without one, React warns in the console and can mix up which row is which.

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
Rewrite the list logic on this page with map, filter and reduce where it makes the code clearer. Always give reduce a starting value, key every list item by a stable id, and explain what each of those lines produces.

Quick check

Sign in to earn +10 XP for it

Chirp's feed shows nothing, but the console logs 20 posts. The code is posts.map((post) => { <PostCard post={post} /> }). What's wrong?

Got a prompt that touches Map, filter and reduce?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.