By: Tristan Pedersen
The findIndex() method of Array is a higher order function; which means it takes a function in as an argument. findIndex() returns the index/position of the first element in the array that matches the condition of the given callback function.
findIndex() will execute the callback function once in ascending order for each element present in the array.
The callback function is invoked for every index of the array. Empty slots in sparse arrays behave the same as undefined.
If findIndex() finds an element where the condition is satisfied and the function returns a truthy value; it will return the index of that element and findIndex() will stop iterating over the remaining values.
If it cannot find an element that satisfies the callback function it will return -1.
Ex.
const data = [3, 5, 18, 150, 40]; const result = data.findIndex((element) => { return element > 100; }); // returns the index of the first number larger than 100. console.log(result); //output: 3 // This is the index of 150, the first number larger than 100.
Summary: findIndex() is an iterative method. It will call a provided callback function once for each element in an array; until the callback function returns a truthy value. Once this happens findIndex() will return the index of that element and will stop iterating through the array. If the callback function never does return a truthy value; findIndex() returns -1.