Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Array findIndex() function in JavaScript
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
<!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 −

Advertisements