Computer >> Computer tutorials >  >> Programming >> Javascript

JavaScript Array findIndex() function


The findIndex() method of JavaScript is used to return the index of the first element in an array, if the condition is passed.

The syntax is as follows −

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

Let us now implement the findIndex() method in JavaScript −

Example

<!DOCTYPE html>
<html>
<body>
   <h2>Rank</h2>
   <button onclick="display()">Result</button>
   <p id="demo"></p>
   <p>Finding the index of the player with highest rank.</p>
   <script>
      var points = [100, 150, 200, 250, 300, 400];
      function topRank(points) {
         return points >= 400;
      }
      function display() {
         document.getElementById("demo").innerHTML = "index = "+points.findIndex(topRank);
      }
   </script>
</body>

Output

JavaScript Array findIndex() function

Click “Result” to get the index −

JavaScript Array findIndex() function

Example

<!DOCTYPE html>
<html>
<body>
   <h2>Rank</h2>
   <button onclick="display()">Result</button>
   <p id="demo"></p>
   <p>Finding the index of the player with specific rank points.</p>
   <script>
      var points = [100, 150, 200, 250, 300, 400];
      function topRank(points) {
         return points == 200;
      }
      function display() {
         document.getElementById("demo").innerHTML = "index = "+points.findIndex(topRank);
      }
   </script>
</body>

Output

JavaScript Array findIndex() function

Above, click the button “Result” −

JavaScript Array findIndex() function