


Hate the complexity of modern front‑end web development? I send out a short email each weekday on how to build a simpler, more resilient web. The following example finds the index of an element in the array that is a prime number (or returns -1 if there is no prime number).*/ if ( ! Array. The findIndex() method in JavaScript is used to search an array for an element that matches a specific condition, and returns the index of the first element. returns the whole item to you, where findIndex returns the index where the item is located in the array. Examples Find the index of a prime number in an array JavaScript Fundamentals - Arrays in JavaScript. If an existing, unvisited element of the array is changed by callback, its value passed to the visiting callback will be the value at the time that findIndex visits that element's index elements that are deleted are not visited. Elements that are appended to the array after the call to findIndex begins will not be visited by callback. The range of elements processed by findIndex is set before the first invocation of callback. If it is not provided, then undefined is used.įindIndex does not mutate the array on which it is called. If a thisArg parameter is provided to findIndex, it will be used as the this for each invocation of the callback. Unlike some other array methods such as Array#some, in sparse arrays the callback is called even for indexes of entries not present in the array.Ĭallback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. 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 index for that iteration. The findIndex method executes the callback function once for every array index 0.length-1 (inclusive) in the array until it finds one where callback returns a truthy value (a value that coerces to true). Return valueĪn index in the array if an element passes the test otherwise, -1. Object to use as this when executing callback. array The array findIndex was called upon. index The index of the current element being processed in the array. findIndex(callback ) Parameters callback Function to execute on each value in the array, taking three arguments:Įlement The current element being processed in the array.
