Latest Code Tutorials

Javascript Array FindIndex Example | Array.prototype.findIndex() Tutorial


Javascript Array FindIndex Example | Array.prototype.findIndex() Tutorial is today’s topic.  The javascript array findIndex() method returns an index of the first item in an array that satisfies the provided callback function. Otherwise, it returns -1, indicating no element passed the test. The findIndex() method executes a function once for each item present in an array. If it finds the array element where the function returns the true value, then the findIndex() returns an index of that array element (and does not check the remaining values). Otherwise, it returns -1.

If you want to learn more about the latest Javascript tutorials then check out this The Complete Javascript Course 2018.

Javascript Array findIndex Example

The findIndex() does not execute the function for array elements without values. The findIndex() does not change the original array. The findIndex() method executes the callback function once for every array index 0..length-1 (inclusive) in an array until it finds one where the provided function returns a true value (a value that coerces to true). The syntax of javascript array findIndex() method is following.

array.findIndex(function(currentValue, index, arr), thisValue)

The function is the required argument. It will run for every item in an array.

The currentValue is the required parameter. It is the value of the current item.

The index is an optional parameter. It is an array index of the current element.

The arr is an optional parameter. It is the current array object.

The thisValue is an optional parameter. The value to be passed to a function to be used as its “this” value.

Now, let us take a simple example.

// app.js

let ages = [3, 10, 18, 20];

console.log(ages.findIndex(age => age > 10));

In above example, we have defined an array and the call the findIndex() function on that array. Pass the arrow function which checks if the item in the array is higher then 10. If the item value > 10 found, then it will log the index of that item. Run that file by typing the node app on the terminal.


Javascript Array FindIndex Example | Array.prototype.findIndex() Tutorial

So the first item which is higher than 10 is 18, and its index is 2. So 2 is logged on the console.

The findIndex() method will return the index based on the written logic inside the given function. The main difference between findIndex() and indexOf() is that we need to give the element to the indexOf() function where on the other side the findIndex() method expect a function which has defined the logic on which we get the index.

At last, Javascript Array FindIndex Example | Array.prototype.findIndex() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.