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.const students = [
{ name: 'john', age: 36 },
{ name: 'jane', age: 34 },
{ name: 'foo', age: 32 },
{ name: 'bar', age: 31 },
{ name: 'jane', age: 33 },
];
// implement findStudentByName with Array.prototype.find
console.log(findStudentByName(students, 'jane'));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.const students = [
{ name: 'john', age: 36 },
{ name: 'jane', age: 34 },
{ name: 'foo', age: 32 },
{ name: 'bar', age: 31 },
{ name: 'jane', age: 33 },
];
// implement findStudentsByName with Array.prototype.filter
console.log(findStudentsByName(students, 'jane'));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.// match each task to the right Array method:
// (a) every winning ticket
// (b) position of first overdue invoice
// (c) one matching user recordPredict 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.const empty = [];
console.log(empty.find((x) => x > 0));
console.log(empty.filter((x) => x > 0));