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

 Live Demo

<!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

Click “Result” to get the index −

Example

 Live Demo

<!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

Above, click the button “Result” −


Advertisements