Finding One Element

filter gives you all the matches. Often you only need one answer: the first match, where it is, or whether a value is in the array at all. Three methods answer these questions:

const nums = [5, 3, 8, 1, 9];

console.log(nums.find(n => n > 6));
console.log(nums.findIndex(n => n > 6));
console.log(nums.includes(8));
console.log(nums.includes(7));

Output:

8
2
true
false
  • find returns the first element for which the callback returns true. Here that is 8. The 9 also matches, but find returns only the first match.
  • findIndex returns the index of that element. The 8 is at index 2.
  • includes takes a value, not a callback. It tells you whether that exact value is in the array.

"Exact" means the type matters too. The string "8" is not the number 8:

<!-- continues -->
console.log(nums.includes("8"));

Output:

false

What if nothing matches?

<!-- continues -->
console.log(nums.find(n => n > 100));
console.log(nums.findIndex(n => n > 100));

Output:

undefined
-1

find returns undefined, and findIndex returns -1. A real index is never negative, so -1 clearly means "not found".

Check for these values before you use the result. Here is a mistake that is easy to miss. If you pass -1 to .at(), you get the last element instead of an error:

<!-- continues -->
const pos = nums.findIndex(n => n > 100);
console.log(nums.at(pos));

if (pos === -1) {
  console.log("not found");
}

Output:

9
not found

Nothing was found, but nums.at(pos) still printed 9. The if check is the safe way.

includes also reads well inside an if. A line like if (allowed.includes(name)) says exactly what it checks.

In the exercise, find the first number over a threshold, find its index, and check whether the array includes 8.