Higher-Order Array Methods
Finding a Match
Return the first element that matches a test.
Finding a Match
find_match.js
const wanted = 3;
const ids = [1, 3, 4, 7];
const found = ids.find((id) => id === wanted);
const label = found === undefined ? "none" : String(found);
console.log("wanted=" + wanted);
console.log("found=" + label);
Stop at the First Match
- Start with
ids:[1, 3, 4, 7]. findchecks one id at a time.- The first
trueresult is returned. - Later ids are not checked after a match is found.
| Checked id |
id === wanted| What happens | | --- | --- | --- | |1| false | keep looking | |3| true | return3| |4| not checked | already stopped |
find-match
`find` stops when the callback first returns `true`. If nothing matches, it returns `undefined`.
Exercise: find_match.js
Use find to return the first matching id, then print none when no id matches