map & filter on Object Arrays

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Extracting One Property

Imagine you have a team array of Codémon objects, and you want a simple array containing only their names — or only their levels. The `.map()` method transforms each object into the exact value you return:

const team = [ { name: "Aquachu", level: 12 }, { name: "Pyrochu", level: 8 }, { name: "Zap", level: 4 } ]; const names = team.map((cdm) => cdm.name); console.log(names);

Combined with parameter destructuring, extracting a property becomes even shorter and cleaner:

const team = [ { name: "Aquachu", level: 12 }, { name: "Zap", level: 4 } ]; const levels = team.map(({ level }) => level); console.log(levels);

Exercise 2 — Building New Objects

Instead of extracting a single value, `.map()` can also return a new object for each item. By combining `.map()` with the spread operator (`...`), you can update every object in a list without mutating the original array:

const team = [ { name: "Aquachu", level: 12 } ]; const levelled = team.map((cdm) => ({ ...cdm, level: cdm.level + 1 })); console.log(levelled[0].level); console.log(team[0].level);

Wrap it in parentheses

In an arrow function, JavaScript treats `{ ... }` right after `=>` as the function's code block, not an object! To return an object literal directly, wrap it in parentheses: `(cdm) => ({ ...cdm })`.

Exercise 3 — Quiz: What Comes Out?

What does `result` contain?

const shop = [ { name: "Potion", price: 30 }, { name: "Map", price: 45 } ]; const result = shop.map(({ price }) => price);
Options
• [30, 45]
• ["Potion", "Map"]
• 75
• []

Hint : The callback returns one value per object.

Exercise 4 — Just the Names

Build an array containing only the names.

Hint : You need a new array of the same length, holding one property of each object.

Exercise 5 — Selecting by a Property

`filter` keeps whole objects, based on a test that looks at one of their properties:

const team = [ { name: "Aquachu", hp: 40 }, { name: "Pyrochu", hp: 0 }, { name: "Zap", hp: 25 } ]; const ready = team.filter((cdm) => cdm.hp > 0); console.log(ready.length); console.log(ready[0].name);

The result is still a list of objects, one that you can filter again, map, or count.

Exercise 6 — Filter Then Map

The pair works best chained: select the objects you care about, then extract what you want to show. That's the most common two-step in all of JavaScript:

const team = [ { name: "Aquachu", hp: 40 }, { name: "Pyrochu", hp: 0 }, { name: "Zap", hp: 25 } ]; const readyNames = team .filter((cdm) => cdm.hp > 0) .map((cdm) => cdm.name); console.log(readyNames);

Filtering first also means `map` runs on fewer elements. And a chain like this reads as a sentence: keep the ones still standing, then take their names.

Exercise 7 — Quiz: Chained on Objects

What does `result` contain?

const team = [ { name: "Aquachu", level: 12 }, { name: "Zap", level: 4 }, { name: "Metachu", level: 15 } ]; const result = team .filter((cdm) => cdm.level >= 10) .map((cdm) => cdm.name);
Options
• ["Aquachu", "Metachu"]
• ["Aquachu", "Zap", "Metachu"]
• [12, 15]
• 2

Hint : Apply the selection first, then the extraction on what's left.

Exercise 8 — Names of the Veterans

Keep the members of level 10 or more, then take their names.

Hint : First select the objects, then transform what remains.

Exercise 9 — Counting Without a Loop

A chain ending with `length` answers "how many?" in one line, with no counter to manage:

const team = [ { name: "Aquachu", type: "water", hp: 40 }, { name: "Pyrochu", type: "fire", hp: 0 }, { name: "Zap", type: "electric", hp: 25 } ]; console.log("Ready: " + team.filter((cdm) => cdm.hp > 0).length); console.log("Fire types: " + team.filter((cdm) => cdm.type === "fire").length);

Exercise 10 — Which Method for Which Job?

`team` is an array of objects. Match each need with the method that answers it.

Items to match
• All the names
• Only the ready ones
• The one named Zap
• How many are ready
Definitions
• team.map(...)
• team.filter(...)
• team.find(...)
• team.filter(...).length

Exercise 11 — Shop Window

Build the shop's display using array methods only. No `for` loops, no manual counters.

Step 1: print one line per item, in the format `"name: X gold"`. Step 2: build `affordable`, the names of the items costing 50 gold or less, and print one per line with `"* "` in front. Step 3: print `"In stock: N"` with the number of items whose `stock` is above 0. Step 4: build `discounted`, a new list of objects identical to `items` but with every price halved, then print the first one's price. The original `items` must stay untouched, so print its first price too.

Expected output:

Potion: 30 gold Elixir: 120 gold Map: 40 gold * Potion * Map In stock: 2 Discounted: 15 Original: 30
Starter code
const items = [ { name: "Potion", price: 30, stock: 5 }, { name: "Elixir", price: 120, stock: 0 }, { name: "Map", price: 40, stock: 2 } ]; // Write your code here
Back to the course