JavaScript
findIndex and some
Learn findIndex for the first matching index and some for any match.
First index matching a condition with findIndex
The findIndex method takes a predicate function and returns the index of the first element that satisfies it. If none does, it returns -1.
Example: [10, 25, 30].findIndex(n => n > 20) returns 1. Because 25 is the first element greater than 20 and its index is 1.
The predicate returns true/false for each element; findIndex takes the first index where it returns true.
At least one element with some
The some method takes a predicate function and returns true if at least one element satisfies it. If none does, it returns false.
Example: [5, 12, 8].some(n => n > 10) returns true because 12 is greater than 10. [1, 2, 3].some(n => n > 10) returns false.
some short-circuits: it stops at the first true and does not check the rest.
Exercise Find the first index greater than 50 in scores
Create an array named scores with at least four numbers. Use scores.findIndex to find the index of the first element greater than 50 and print the result with console.log.
Show example solution
Write the array, then find the first element greater than 50 with scores.findIndex and print the result.
Example solution:
const scores = [10, 30, 60, 80];
const i = scores.findIndex(s => s > 50);
console.log(i);
Exercise Check whether ages has a value under 18
Create an array named ages with at least four numbers. Use ages.some to check whether there is an age under 18 and print the result with console.log.
Show example solution
Write the array, then check with ages.some whether there is an age under 18 and print the result.
Example solution:
const ages = [25, 30, 15, 40];
const hasMinor = ages.some(a => a < 18);
console.log(hasMinor);
Test yourself
-
What does this code print?
const nums = [5, 12, 8, 30];
const i = nums.findIndex(n => n > 20);
console.log(i);
Show answer
3 — Correct. 30 is the first element greater than 20; its index is 3.
-
Check whether any number is greater than 10
const nums = [5, 12, 8];
const hasBig = nums.some(n => n > ____);
console.log(hasBig);
Show answer
const nums = [5, 12, 8];
const hasBig = nums.some(n => n > 10);
console.log(hasBig);
-
Match each method with its job
- findIndex
- first index matching predicate
- some
- is any element true
- indexOf
- first index equal to value
Next lesson: Summary - Array iteration