findIndex()

The findIndex method in JavaScript arrays is designed to return the index of the first element in the specified array that meets the criteria defined by the provided function. In cases where no element fulfills the condition, the method will return -1.

Syntax

The syntax for the findIndex function is as follows:

Example

array.findIndex(callback(value,index,arr),thisArg)

Parameter

callback - It denotes the function responsible for executing each individual element.

value - The current element of an array.

index - This parameter is optional. It represents the index of the current element.

arr - This parameter is not mandatory. It refers to the array that the findIndex function is applied to.

thisArg - This parameter is not mandatory. It specifies the value to be utilized as this during the execution of the callback function.

Return

The position of the initial element within the array that meets the criteria set by the function condition.

JavaScript Array findIndex method example

Let's see some examples of findIndex method.

Example 1

Let's see a simple example of findIndex method.

Example

<script>

var arr=[5,22,19,25,34];

var result=arr.findIndex(x=>x>20);

document.writeln(result)

</script>

Output:

Example 2

In this illustration, we will determine the index of a prime number by utilizing the findIndex function.

Example

<script>

function isPrime(value, index, arr) {

  var start = 2;

  while (start <= Math.sqrt(value)) {

    if (value % start++ < 1) {

      return false;

    }

  }

  return value > 1;

}

document.writeln([8, 4, 7, 22].findIndex(isPrime));

</script>

Output:

Input Required

This code uses input(). Please provide values below: