Finding Elements: find(), some(), every()
To find one animal by its name, you'd write a loop with break, as in the lesson on loops:
let leo;
for (const animal of animals) {
if (animal.name === "Leo") {
leo = animal;
break;
}
}
console.log(leo);{ name: "Leo", species: "lion", age: 6 }let leo; creates a variable without a value, so it holds undefined until the loop finds Leo. The method find() does the same in one line. It returns the first element for which the callback returns true, and just like break, it stops looking there:
const leo = animals.find((animal) => animal.name === "Leo");
console.log(leo.species);lionUnlike filter(), which always returns an array, find() returns the element itself. When no element meets the condition, it returns undefined. Reading a property of undefined ends the program with an error, so check the result first:
const tiger = animals.find((animal) => animal.species === "tiger");
if (tiger === undefined) {
console.log("We have no tiger.");
} else {
console.log(tiger.name);
}We have no tiger.Sometimes you don't need the element, just a yes or a no. some() returns true when the callback returns true for at least one element. every() returns true only when the callback returns true for all of them:
console.log(animals.some((animal) => animal.age > 10));
console.log(animals.every((animal) => animal.age > 3));true
falseElla is older than 10, so some() returns true. Pip is only 2, so not every animal is older than 3, and every() returns false.
A typical mistake is to use filter() when you want one element. animals.filter((animal) => animal.name === "Leo").species gives undefined: filter() returns an array with Leo in it, and the array has no property species.
Instructions
Use find() to find the book whose title is in wanted, and print its author: Michael Ende. If the library has no such book, print We don't have it. instead. Try it: change wanted to "Heidi", and then back.
Below, use some() to print whether at least one book is available: Some available: true. Tip: available is already true or false, so the callback can return it as it is.
Finally, use every() to print whether all the books are available: All available: false.