filter and find
You'll learn to keep some items of a list with filter, and to get one item with find.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You have a class list and you want only the students who passed. Or you want the one student called Nusrat. Both jobs mean looking at each item and asking a yes or no question.
Like map, both take a function, the callback. Here the callback answers a question with true or
false for each item: "did this student pass?"
const passed = students.filter(s => s.marks >= 33);const nusrat = students.find(s => s.name === "Nusrat");
filter always gives back a new array with every item where the callback said true. It can hold
many items, one item, or none. When nothing matches, you get an empty array, [].
find gives back one item: the first one where the callback said true, and then it stops looking.
It does not wrap the item in an array. When nothing matches, you get undefined.
People often use filter when they want one thing, and then write result.name. But result is an
array, so result.name is undefined. If you want one item, use find. If you want a list, use
filter.
The other common slip is forgetting that find can give undefined. Before you read nusrat.name,
make sure nusrat was found.
When you read these calls, look at the callback and ask: for which items is this true? Then ask: do I
get a list, or one item?
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1const prices = [120, 450, 80, 600];2console.log(prices.filter(p => p > 300));3console.log(prices.find(p => p > 300));
findStudent should give back one student object, or undefined if nobody has that name. passedStudents should give back an array of everyone with 33 or more. The two functions use the wrong method. Fix them so all four checks pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3What is
[20, 35, 50].filter(n => n > 100)? - 2 / 3What is
[20, 35, 50].find(n => n > 30)? - 3 / 3
findfinds nothing. What do you get?
Explain it back
How confident are you with filter and find?
Done
filter or find call and say exactly what it gives back, including when nothing matches.