
searched item: usually a number or a string.Unlike find() and findIndex() methods, indexOf() can take to parameters: The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. Slow performance compared to other approaches.Ĭheck out MDN full docs on findIndex() method.īrowser support for findIndex(): () method browser support indexOf() method.Ability to find an item if it is an object.Callback function allows to handle complex logic.Straightforward and easy to understand syntax.findIndex ( number => number = ' five ' ) console. The following example returns the index of the first element in the array that is a prime number, or -1 if there is no prime number.Const numbers = const itemIndex = numbers. Examples Find the index of a prime number in an array Elements that are deleted are still visited. If an existing, unvisited element of the array is changed by callback, its value passed to the callback will be the value at the time findIndex visits the element's index. callback will not process the elements appended to the array after the call to findIndex begins. The range of elements processed by findIndex is set before the first invocation of callback. If it is not provided, then undefined is used. If a thisArg parameter is passed to findIndex, it will be used as the this inside each invocation of the callback. Unlike other array methods such as Array.some, the callback is called even for indexes with unassigned values.Ĭallback is invoked with three arguments: If the callback never returns a truthy value (or the array's length is 0), findIndex returns -1. If such an element is found, findIndex immediately returns the element's index. The findIndex method executes the callback function once for every index 0.length-1 (inclusive) in the array until it finds the one where callback returns a truthy value (a value that coerces to true). The index of the first element in the array that passes the test. thisArg Optional Optional object to use as this when executing callback. array Optional The array findIndex was called upon. index Optional The index of the current element being processed in the array. It takes three arguments:Įlement The current element being processed in the array. Syntax arr.findIndex (callback(element])) Parameters callback A function to execute on each value in the array until the function returns true, indicating that the satisfying element was found.

See also the find() method, which returns the value of an array element, instead of its index. If you'd like to contribute to the interactive examples project, please clone and send us a pull request.


The source for this interactive example is stored in a GitHub repository.
