JavaScript(JS) array method - findindex

The findIndex() method is an array method in JavaScript that returns the index of the first element in the array that satisfies a specified testing function. If no such element is found, -1 is returned.

Here's the syntax of the findIndex() method:

refer to‮gi:‬iftidea.com
array.findIndex(callback, thisArg);
  • array is the array that the findIndex() method is called on.
  • callback is a function that takes three arguments: the current value of the element being processed, the index of the element being processed, and the array that the findIndex() method was called on. This function should return a boolean value indicating whether the element satisfies the test or not.
  • thisArg is an optional argument that specifies the value of this inside the callback function.

The findIndex() method iterates through the array and calls the callback function on each element. If the callback function returns true for an element, the findIndex() method returns the index of that element and stops iterating. If no element satisfies the test, the findIndex() method returns -1.

Here's an example of how to use the findIndex() method:

let array = [1, 2, 3, 4, 5];

let foundIndex = array.findIndex(function(element) {
  return element > 2;
});

console.log(foundIndex); // 2

In this example, we have an array array containing the elements [1, 2, 3, 4, 5]. We use the findIndex() method to find the index of the first element that is greater than 2. The callback function checks whether the current element is greater than 2 and returns a boolean value. The findIndex() method iterates through the array and returns the index of the first element that satisfies the test. The console.log() statement outputs the value of foundIndex, which is 2.

Note that the findIndex() method returns only the index of the first element that satisfies the test. If you need to find all the elements that satisfy the test, you can use the filter() method. Also, the findIndex() method was introduced in ECMAScript 6, so it may not be supported by older browsers.