Learn
Iterators
The .findIndex() Method
The .findIndex()
method is particularly useful when we want to find the position of an element that meets a certain criteria. This can be helpful in scenarios such as searching for a specific value, identifying the index of an object with specific properties, or even filtering out unwanted elements from an array.
How does .findIndex() work?
The syntax for using the .findIndex()
method is as follows:
Here's what each component means:
array
: The array that needs to be searched.callback
: A function that is executed on each element of the array. It can take up to three arguments:element
(the current element being processed),index
(the index of the current element being processed), andarray
(the array being traversed).thisArg
(optional): An object to whichthis
can refer to inside the callback function.
The .findIndex()
method returns the index of the first element in the array that satisfies the provided testing function. If no element matches the criteria, it returns -1.
Example:
In this example, we have an array of numbers. We use the .findIndex()
method along with a callback function to find the index of the first number that is greater than 30. The returned index is 3, which corresponds to the element 40
.
Instructions
Declare a variable passingScore
and assign it the value of 80.
Declare a new variable index
that will use the .findIndex()
method on the students
array to find the index of the first student whose score
is greater than or equal to the passingScore
variable.
Print the index
value to the console.
Sign up to start coding
Already have an account?
Sign In