Course outline · 0% complete

0/29 lessons0%

Course overview →

find, some, every

lesson 7-2 · ~9 min · 23/29

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, or undefined if none do.
  • some(test)true if at least one item passes (Python's any).
  • every(test)true if all items pass (Python's all).

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?