×

javascript · level 2 · unit 6 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.