Asking questions of an array
Three more methods take an arrow that answers true or false, but instead of building arrays they answer questions:
find(test)→ the first item that passes, orundefinedif none do.some(test)→trueif at least one item passes (Python'sany).every(test)→trueif all items pass (Python'sall).
They shine on arrays of objects, which is how real data usually arrives:
const users = [ { name: "Ada", age: 36 }, { name: "Alan", age: 41 } ]; const alan = users.find(u => u.name === "Alan"); // the whole object
find hands you the object itself, so alan.age is 41. For simple membership checks on plain values, includes from lesson 4-2 is still the shortest tool.
Code exercise · javascript
Run it. find returns the whole matching object, some and every answer booleans about the group.
Code exercise · javascript
Your turn. Print two lines: the name of the first item that is out of stock (qty of exactly 0), and whether every item costs more than 0.
Quiz
users.find(u => u.age > 200) matches nobody. What comes back?