Search and Check Arrays

In the last lesson, you sorted the watchlist by any property and broke ties with a second key. Sorting reorders every film, but many of Tomás’s questions have one short answer instead. Which record is Coco? Where does it sit in the list? Does every film have at least one vote? A few lessons back, you answered a question like these with a for...of loop that stopped with break once it found a film nobody had seen.

In this lesson, you’ll hand callbacks to array methods that search and check the list for you and stop as soon as they know the answer. You’ll choose the method by the kind of answer you need and handle the case where nothing matches. Start with that loop and find(), the method that replaces it.

Find One Film With find() and findIndex()

When you need one item from a list, building a whole new array with filter() is more than you asked for. The find() method calls your callback for each item, in order, and stops at the first one whose callback returns a truthy value. It returns that item itself, not an array that holds it.

Here’s the search loop from the lesson on chaining and loops, changed so it keeps the film it finds instead of logging a message:

Language: JavaScript
let unseen;
for (const film of watchlist) {
  console.log(`Checking ${film.title}`);
  if (film.seenBy.length === 0) {
    unseen = film;
    break;
  }
}

The loop has three parts: the test in the if, the unseen variable that starts as undefined and receives the result, and the break that stops at the first match. Create a file named search.js, and copy the watchlist array from order.js to the top of the new file. Below it, write the same search with find(). The callback logs each title it checks, as the loop did, so you can see where find() stops:

Language: JavaScript Filename: search.js
const watchlist = [
  { title: "Paddington 2", minutes: 104, genre: "comedy",
    seenBy: ["Tomás", "Aisha"], votes: 3 },
  { title: "Spirited Away", minutes: 125, genre: "animation",
    seenBy: ["Priya"], votes: 2 },
  { title: "The Grand Budapest Hotel", minutes: 99,
    genre: "comedy", seenBy: ["Kenji", "Lucía"], votes: 0 },
  { title: "Arrival", minutes: 116, genre: "sci-fi",
    seenBy: [], votes: 3 },
  { title: "Coco", minutes: 105, genre: "animation",
    seenBy: ["Aisha", "Priya", "Kenji"], votes: 4 },
  { title: "Inception", minutes: 148, genre: "sci-fi",
    seenBy: ["Tomás"], votes: 1 },
];

const unseen = watchlist.find((film) => {
  console.log(`Checking ${film.title}`);
  return film.seenBy.length === 0;
});
console.log(unseen);

Run it:

Language: Shell
$ node search.js
Checking Paddington 2
Checking Spirited Away
Checking The Grand Budapest Hotel
Checking Arrival
{
  title: 'Arrival',
  minutes: 116,
  genre: 'sci-fi',
  seenBy: [],
  votes: 3
}

The callback runs four times and stops at Arrival, as the loop did, so Coco and Inception are never checked. Each part of the loop has moved. The if test is now the callback’s return value. The break is built into find(), which stops at the first truthy return. And the result is no longer assigned inside the loop. It’s the value find() returns, which here is Arrival’s record, so unseen.title works straight away, with no let and no break.

What if nothing matches? Then the loop’s unseen stays undefined, and find() gives the same answer. It checks every film and returns undefined. Reading a property of undefined throws a TypeError, so check the result before you use it.

Sometimes Tomás needs the film’s position rather than the film, for example, to tell the friends how far down the list it is. The findIndex() method takes the same kind of callback and returns the first match’s index. When nothing matches, it returns -1, the same not-found value as indexOf(). Two more methods search from the end of the list: findLast() returns the last match, and findLastIndex() returns its index.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.