JavaScript Array findIndex() Tutorial

In this section, we will see what the Array findIndex() method is and how to use it in JavaScript.

JavaScript Arrays findIndex() Method

Sometimes in an array we’re looking for the index number of an element that it matches a set of conditions.

For example, we want to find index number of the first value in an array that is greater than the value 20! We don’t care if the value is 21 or 100, etc. all we care is that the value should be above 20.

The `findIndex()` method is used in a situation like this.

Basically, the findIndex() method is a way of looking for the index of an element that meets a certain criterion.

Array findIndex() Syntax:

array.findIndex(function(currentValue, index, arr), thisValue)

Array findIndex() Method Parameters:

The `findIndex()` method takes two arguments.

The first argument is a reference to a function. For each element in the target array, the `findIndex()` method will call the reference function.

This function takes 3 arguments:

  • The first argument is the element in the array.
  • The second argument is the index of that element.
  • The third argument is a reference to the target array.

Inside this function, we specify a set of instructions that will be run for each element of the target array and at the end will return either `true` or `false`. As long as the result of this function is `false` the `findIndex() `method will put the next element of the array as the argument to the function and calls it.

But the moment the result of the function becomes true, the `findIndex()` method will return the index number of the element that caused the result `true` and won’t call the function anymore.

Other than the function, the `findIndex()` method takes a second argument as well. This second argument, which is optional, is a reference to an object that will bind to the `this` keyword in the function that we passed as the first argument.

Array findIndex() Method Return Value:

The return value of this method is the index number of an element in an array that met the criteria we’ve defined in the findIndex() method.

Note: if the type of the value that we’re looking for is not in the target array, the return value of this call will be `-1`.

Example: using Array findIndex() method in JavaScript

const arr = [23,4,3,23,4,2,32,5,3,23,423,234,2,3,2423,42];
function eve(value, index, arr){
  return value >=100?true: false; 
}

const final = arr.findIndex(eve);
console.log(final);

Output:

10

In this example, we’re looking for the index number of the first element in the array that is greater than the value of 100.

Here, the first occurrence of an element greater than 100 is 423 and so the engine returned its index number as the final value of the call to the `findIndex()` method.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies