In the last lesson, you handed callbacks to map() and filter(). The map() call turned every film into a label for the group chat, and the filter() call kept only the animated films. Each method did one job. Tomás’s next request needs both at once, and some jobs on the watchlist don’t fit either method.
In this lesson, you’ll combine filter() and map() in one chain, use forEach() when you want to do something with each film without building a new array, and recognize when a plain loop still reads better. Start with Aisha’s request from the last lesson, taken one step further.
Chain filter() and map()
Some tasks need only some of the films and a new value for each one. Aisha wants an animated film tonight, so Tomás wants to post the animated films’ labels for her to choose from. That’s a filter and a transform in one task.
With the loops you already know, you’d write something like this, with an empty array, a test, and a push() inside the test:
const labels = [];
for (const film of watchlist) {
if (film.genre === "animation") {
labels.push(`${film.title} (${film.minutes} min)`);
}
}
The loop works, but it mixes three jobs in one block. The test decides which films count, the template literal builds each label, and the empty array and push() collect the results. The array methods split those jobs apart.
Create a file named chain.js, and copy the watchlist array from helpers.js to the top of the new file. Below the watchlist, write the same task as a chain of filter() and map():
chain.js
const watchlist = [
{ title: "Paddington 2", minutes: 104, genre: "comedy",
seenBy: ["Tomás", "Aisha"], votes: 3 },
{ title: "Spirited Away", minutes: 125, genre: "animation",
seenBy: ["Priya"], votes: 2 },
{ title: "The Grand Budapest Hotel", minutes: 99,
genre: "comedy", seenBy: ["Kenji", "Lucía"], votes: 0 },
{ title: "Arrival", minutes: 116, genre: "sci-fi",
seenBy: [], votes: 3 },
{ title: "Coco", minutes: 105, genre: "animation",
seenBy: ["Aisha", "Priya", "Kenji"], votes: 4 },
{ title: "Inception", minutes: 148, genre: "sci-fi",
seenBy: ["Tomás"], votes: 1 },
];
const animatedLabels = watchlist
.filter((film) => film.genre === "animation")
.map((film) => `${film.title} (${film.minutes} min)`);
console.log(animatedLabels);
Run it from your terminal, and you get the two labels the loop would build:
$ node chain.js
[ 'Spirited Away (125 min)', 'Coco (105 min)' ]
Read the chain from the top. The filter() call returns a new array that holds the two animated films. On the next line, you call .map() on that two-film array, so it builds two labels. It never sees the other four films in watchlist. This is a method chain: each method is called on the array the one before it returned.