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
Returning the first number that equals its index in an array using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of number. Our function should return that first number from the array whose value and 0-based index are the same given that there exists at least one such number in the array.
Example
Following is the code −
const arr = [9, 2, 1, 3, 6, 5];
const findFirstSimilar = (arr = []) => {
for(let i = 0; i < arr.length; i++){
const el = arr[i];
if(el === i){
return i;
};
};
};
console.log(findFirstSimilar(arr));
Output
3
Advertisements