javascript · level 2 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
filter and map to go from data to page in one go.
filter and map both hand back arrays, so you can call the next method straight away: fruit.filter(...).map(...). That is a chain. Put each step on its own line, starting with its dot, and read it top to bottom.
End with .join(", "), which glues an array into one string with a comma and a space between items, ready for .textContent.
Put a chain inside an input listener and you have a live search: every key filters the data again by what was typed.
<input id="search" placeholder="Search fruit">
<p id="results"></p> const fruit = ["apple", "banana", "cherry", "grape", "pear"];
const search = document.querySelector("#search");
const results = document.querySelector("#results");
search.addEventListener("input", () => {
results.textContent = fruit
.filter((name) => name.includes(search.value))
.map((name) => name.toUpperCase())
.join(", ");
}); Press run it to bring the page to life.
console
nothing logged yet
Type ap into the box and watch APPLE and GRAPE appear.
guess first
5 is typed into the price box. What shows?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<input id="max" type="number" placeholder="Most you will pay">
<p id="deals"></p> const toys = [{ name: "Yo-yo", price: 3 }, { name: "Kite", price: 8 }, { name: "Ball", price: 5 }];
const max = document.querySelector("#max");
max.addEventListener("input", () => {
document.querySelector("#deals").textContent = toys
.filter((toy) => toy.price <= Number(max.value))
.map((toy) => `${toy.name} £${toy.price}`)
.join(" | ");
});
your turn
Your turn. Build a film search.
Fill in the method that keeps only the matching films, then choose what goes between the names. Press run and type o in the box.
the page your code works on
<input id="box" placeholder="Search films">
<p id="films"></p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- typing o finds Frozen and Moananot checked yet
fix it
The veggie button empties the menu. Fix it!
the page your code works on
<button id="veggie">Veggie only</button>
<p id="menu">Soup, Burger, Salad</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- only the veggie meals are listednot checked yet
- The menu ends up empty. What does the array look like after the
mapline? - After
map, each item is only a name, with noveggiekey left to test. Filter while the items are still whole meals. - Swap lines 4 and 5, so filter comes before map, then press run.
nailed it
you chained your way from data to page. :D
filter,mapandjoincan be chained one after another.- Each step works on the answer of the step before.
- A chain inside an
inputlistener makes a live search.
new words in your collection
- chain
This lesson isn’t saved. A free account remembers every lesson you finish.