In this lesson, you turned Tomás’s watchlist into labels for the group chat and picked out the animated films, by handing a callback to array methods instead of writing a loop.
Key Points
- A loop that builds a new array always has an empty array, the loop itself, and a
push()call. Only the expression that builds each new item changes. Withmap()andfilter(), you hand in that part as a callback. map()calls your callback once for each item, in order, and passes the item in. Each return value goes into a new array at the same position, so the result always has the same length as the original.filter()also calls your callback once for each item, but it doesn’t collect the return values. It keeps the item itself when the callback returns a truthy value and leaves it out otherwise. A count works as a test, because0is falsy.- The callback’s return decides the result. Your
isShorthelper takes minutes, butmap()andfilter()hand the callback the whole film, sofitsTonighttakes a film. HandfitsTonightto both, andmap()gives back sixtrueorfalsevalues, whilefilter()gives back the four films that fit. - Neither method changes the original array. Each one builds a new array and returns it. The films that
filter()returns are the watchlist’s own records, so a change to one would show in both. - If you give an arrow a braces body, it needs a
returnstatement, or every valuemap()collects isundefined.
Final Code
This script starts with the watchlist array from helpers.js in the Store Functions in Variables lesson, then transforms and filters it: