JavaScript Array findIndex()

Posted by

Method

Introduction to the JavaScript Array findIndex() Method

The Array findIndex() method is used to find the index of the first element in an array that fulfills a given condition. It returns the index of the element that satisfies the given condition, else it returns -1. The syntax of the findIndex() method is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

array.findIndex(callback[, thisArg])

[/dm_code_snippet]

The callback parameter is a function that is used to test each element for the condition. If the condition is true for the element, then the index of the element is returned, else -1 is returned.

The thisArg parameter is optional. It is used to set the value of this inside the callback function.

Example of the JavaScript Array findIndex() Method

To understand the findIndex() method, let’s look at the following example.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let numbers = [2, 3, 4, 10, 20];

let index = numbers.findIndex(element => element > 5);

console.log(index);

[/dm_code_snippet]

In this example, we have an array of numbers and we are using the findIndex() method to find the index of the first element in the array that is greater than 5. The callback function is used to test each element in the array and the condition is fulfilled if the element is greater than 5.

In this case, the index of the element 10 is returned, which is 3.

Using the thisArg Parameter

The thisArg parameter is optional and can be used to set the value of this inside the callback function. Let’s look at the following example to understand how to use the thisArg parameter.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let numbers = [2, 3, 4, 10, 20];

let index = numbers.findIndex(function(element, index){
  return element > this;
}, 5);

console.log(index);

[/dm_code_snippet]

In this example, we are using the findIndex() method to find the index of the first element in the array that is greater than 5. The thisArg parameter is used to set the value of this inside the callback function to 5.

In this case, the index of the element 10 is returned, which is 3.

Conclusion

In conclusion, the Array findIndex() method is used to find the index of the first element in an array that satisfies a given condition. It returns the index of the element that satisfies the given condition, else it returns -1. The thisArg parameter is optional and can be used to set the value of this inside the callback function.