Higher-Order Array Methods
Finding a Match
Return the first element that matches a test.
find-match
`find` stops when the callback first returns `true`. If nothing matches, it returns `undefined`.
Finding a Match
find_match.js
Replay: real traced execution (multi-file project)
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);
const wanted = 4;
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);
const wanted = 9;
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);
wanted ← 3, ids ← 1,3,4,7, found ← 3, label ← 3
1const wanted→ 3 = 3; //@wanted=4, 92const ids→ 1,3,4,7 = [1, 3, 4, 7];3const found→ 3 = ids1,3,4,7.find((id) => id === wanted);4const label→ 3 = found→ 3 === undefined ? "none" : String(found3);56console.log("wanted=" + wanted3);7console.log("found=" + label3);outputwanted=3 found=3
wanted ← 4, ids ← 1,3,4,7, found ← 4, label ← 4
1const wanted→ 4 = 4;2const ids→ 1,3,4,7 = [1, 3, 4, 7];3const found→ 4 = ids1,3,4,7.find((id) => id === wanted);4const label→ 4 = found→ 4 === undefined ? "none" : String(found4);56console.log("wanted=" + wanted4);7console.log("found=" + label4);outputwanted=4 found=4
wanted ← 9, ids ← 1,3,4,7, found ← undefined, label ← none
1const wanted→ 9 = 9;2const ids→ 1,3,4,7 = [1, 3, 4, 7];3const found→ undefined = ids1,3,4,7.find((id) => id === wanted);4const label→ none = found→ undefined === undefined ? "none" : String(foundundefined);56console.log("wanted=" + wanted9);7console.log("found=" + labelnone);outputwanted=9 found=none
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 |
Exercise: find_match.js
Use find to return the first matching id, then print none when no id matches