Question Bank
JavaScript find vs filter for Student Lookup Quiz
Difficulty: Easy
Two seeded approaches to look up students by name: `find` returns the first match, `filter` returns every match. Two companions cover return-type pitfalls and short-circuit semantics.
JavaScript find vs filter for Student Lookup Quiz
Two seeded approaches to look up students by name: `find` returns the first match, `filter` returns every match. Two companions cover return-type pitfalls and short-circuit semantics.
807 views
20
Implement findStudentByName(students, name) using Array.prototype.find so it returns the first student object whose name matches, or undefined if none match.
Examples
Example 1:
Input: findStudentByName(students, 'jane')
Output: { name: 'jane', age: 34 }
Explanation: find walks left to right and returns the first matching element, so the older Jane is returned.Implement findStudentsByName(students, name) using Array.prototype.filter so it returns every student object whose name matches, or an empty array if none match.
Examples
Example 1:
Input: findStudentsByName(students, 'jane')
Output: [{ name: 'jane', age: 34 }, { name: 'jane', age: 33 }]
Explanation: filter visits every element and collects each one that satisfies the predicate, preserving original order.Pick the correct method (find, filter, or findIndex) for each task: (a) get every winning ticket, (b) get the position of the first overdue invoice, (c) get one matching user record. Explain the return-type difference.
Examples
Example 1:
Input: tasks (a), (b), (c)
Output:
(a) filter -> array of matches
(b) findIndex -> integer index or -1
(c) find -> single element or undefined
Explanation: filter gives you all matches, findIndex gives a position, find gives the first matching element.Predict the output of running find and filter against an empty array, and show how each result should be checked safely at the call site.
Examples
Example 1:
Input: [].find(x => x > 0)
Output: undefined
Explanation: find returns undefined when no element matches (including the empty case).Example 2:
Input: [].filter(x => x > 0)
Output: []
Explanation: filter always returns an array, so an empty input yields an empty array.