Code of the Day
BeginnerLanguage basics

Lab: shaping data

Practice map, filter, and reduce by transforming arrays of objects.

Lab · optionalJavaScript / TSBeginner16 min
Recommended first
By the end of this lesson you will be able to:
  • Transform arrays with map, filter, and reduce
  • Work with arrays of objects
  • Prefer expressive array methods to manual loops

Optional lab. Hands-on with the array methods that power most real JavaScript — write, run, check.

Same job, two styles

Run this to compare a manual loop with the filter + map chain. Same result; the chain says what you want, not how to step through it:

JavaScript — editable, runs in your browser

Checkpoint 1 — total a cart

Each item has a price and a qty. Write totalPrice to sum price * qty across the cart with reduce.

Total a shopping cartJavaScript

Write totalPrice(items) returning the sum of price * qty over all items. Each item is { price, qty }. An empty cart totals 0.

totalPrice([{price:2,qty:3},{price:5,qty:1}])11

Give reduce a starting value of 0 so the empty-cart case works: items.reduce(function (sum, item) { return sum + item.price * item.qty; }, 0).

Checkpoint 2 — active user names

Combine filter and map: from a list of users, return just the names of the active ones, in order.

Names of active usersJavaScript

Write activeNames(users) returning an array of the names of users whose active is true, preserving order. Each user is { name, active }.

activeNames([{name:'a',active:true},{name:'b',active:false}])['a']

users.filter(function (u) { return u.active; }).map(function (u) { return u.name; }) reads as exactly what it does — the payoff of expressive methods over loops.

Done?

Two green checks and you can reshape data fluently — the everyday work of most JavaScript. That wraps the beginner labs for this module.

Finished reading? Mark it complete to track your progress.

On this page