Learn JavaScript · lesson 33 of 60 · about 7 minutes
map() and filter()
Add a search box to Sam's page: list every title with map, and keep the matching posts with filter.
What you'll learn
- Transform arrays with map()
- Select items with filter()
- Chain methods together
A search box
Sam has enough posts now that visitors want to search them. Writing another for...of loop for every question gets long, so arrays have methods that take a small function and run it on each item. posts.map((post) => post.title) makes a new array of just the titles, and posts.filter(...) keeps only the posts whose title includes what the visitor typed.
Give the array a function
Array methods take a function and call it for each item:
map(fn)returns a new array with fn applied to every itemfilter(fn)returns a new array of items where fn returned true
The original array isn't changed.
map and filter
const prices = [4, 12, 7, 20];
const doubled = prices.map((p) => p * 2);
const cheap = prices.filter((p) => p < 10);
console.log(doubled.join(", "));
console.log(cheap.join(", "));
console.log(prices.join(", "));Output
8, 24, 14, 40
4, 7
4, 12, 7, 20Chaining
Because each method returns an array, you can chain them: filter first, then map.
Names of players who passed
const players = [
{ name: "Ada", score: 82 },
{ name: "Bo", score: 45 },
{ name: "Cy", score: 67 },
];
const passed = players.filter((p) => p.score >= 50).map((p) => p.name);
console.log(passed.join(" & "));Output
Ada & CyTip
Every string includes the empty string, so "hello".includes("") is true. A search for nothing would match every post: check for an empty search first.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.