π 1. find()
β
Purpose:
Finds the first element in the array that matches a condition.
β
Example
const numbers = [10, 20, 30, 40];
const result = numbers.find(num => num > 25);
console.log(result); // π 30
It stops when it finds the first match.
Task
- Imagine you have a list of days of the month when you have to go to gym, and you want to find the first even day when you have to go to gym. gymDays = [3, 5, 8, 11, 14, 15, 21, 26, 29].
- Imagine you have a list of studentsβ exam scores, and you want to find the first student who scored above the passing mark so you can congratulate them. scores = [35, 42, 38, 50, 45, 30, 60]
π’ 2. findIndex()
β
Purpose:
Finds the index of the first matching element.
β
Example:
const numbers = [5, 10, 15, 20];
const index = numbers.findIndex(num => num > 12);
console.log(index); // π 2 (because 15 is at index 2)
If nothing matches, it returns -1.
Task
- Find the index of first negative number [5, 3, 0, -2, -5]