The findIndex() method returns the index of the first element in an array that pass a test.
The findIndex() method returns the index of the first element in an array that pass a test.
The findIndex() method executes the function once for each element present in the array:
findIndex() does not run the function for array elements without values.
findIndex() does not change the original array.
array.findIndex(function(currentValue, index, arr), thisValue)
Parameter | Require | Description |
---|---|---|
function(currentValue, index,arr) | Required. | A function to be run for each element in the array. |
thisValue | Optional. | A value to be passed to the function to be used as its "this" value. If this parameter is empty, the value "undefined" will be passed as its "this" value |
For function(currentValue, index,arr)
Argument | Require | Description |
---|---|---|
currentValue | Required. | The value of the current element |
index | Optional. | The array index of the current element |
arr | Optional. | The array object the current element belongs to |
Returns the array element index if any of the elements in the array pass the test, otherwise it returns -1
Get the index of the first element in the array that has a value of 18 or more:
var ages = [3, 10, 18, 20]; function checkAdult(age) { return age >= 18; } console.log( ages.findIndex(checkAdult));
Array findIndex() method returns the index position.
If none of the elements in the collection match the callback (element, index, array) criteria, the return value is -1.
The syntax for the find() method looks like this:
arr.findIndex(callback[, thisArg])
function callback(element, index, array) { // returns true or false based on some condition }
const inventory = [ {name: 'XMLs', quantity: 2}, {name: 'Screens', quantity: 0}, {name: 'Keyboards', quantity: 5} ]; result = inventory.findIndex((fruit) => fruit.name === 'XMLs'); console.log(result); // 0 result = inventory.findIndex((fruit) => fruit.name === 'grapes'); console.log(result); // -1