Need one matching item from an array, rather than every match? `find` takes a callback that tests each item and returns the first item for which the callback returns true. If nothing matches, it returns `undefined`. section 10.1.4
Listing 10.8 Finding and filtering array items
const ninjas = [
{ name: "Yagyu", weapon: "shuriken" },
{ name: "Yoshi" },
{ name: "Kuma", weapon: "wakizashi" },
];
const ninjaWithWakizashi = ninjas.find((ninja) => { #A
return ninja.weapon === "wakizashi"; #A
}); #A
console.assert(
ninjaWithWakizashi?.name === "Kuma" && #B
ninjaWithWakizashi.weapon === "wakizashi",
"Kuma is wielding a wakizashi",
);
const ninjaWithKatana = ninjas.find((ninja) => {
return ninja.weapon === "katana";
});
console.assert(
ninjaWithKatana === undefined,
"We couldn't find a ninja that wields a katana",
);
const armedNinjas = ninjas.filter( #C
(ninja) => "weapon" in ninja, #C
); #C
console.assert(
armedNinjas[0].name === "Yagyu" &&
armedNinjas[1].name === "Kuma",
"Yagyu and Kuma are armed",
);
The lookup for a wakizashi returns the matching ninja; the lookup for a katana returns `undefined`. The same listing uses `filter` when the goal is to collect all matching items. section 10.1.4
Account for a missing result before reading its properties; the example uses optional chaining when checking the found item's name. Choose `filter` instead when you need an array of every match, or `some` when you only need to know whether a match exists. section 10.1.4




