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 −

 Live Demo

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

Updated on: 20-Apr-2021

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements