Array findIndex() function in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

The findIndex() function in JavaScript returns the index of the first element value that satisfy a given condition in an array.

Following is the code for the array find() function −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .findIndex {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Array FindIndex() example</h1>
<div class="findIndex"></div>
<button class="findArr">CLICK HERE</button>
<h3>Click on the above button to get the index of lion in the array</h3>
<script>
   function findLion(animal) {
      return animal === "lion";
   }
   let fillEle = document.querySelector(".findIndex");
   let arr = ["cow", "lion", "bull", "tiger"];
   fillEle.innerHTML = arr;
   document.querySelector(".findArr").addEventListener("click", () => {
      fillEle.innerHTML = arr.findIndex(findLion);
   });
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button the index of lion will be returned as follows −

raja
Published on 08-May-2020 14:15:12
Advertisements