Returning the first number that equals its index in an array using JavaScript

Problem

We need to write a JavaScript function that takes an array of numbers and returns the first number whose value equals its 0-based index position. This means we're looking for an element where array[i] === i.

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));
3

How It Works

The algorithm iterates through each array element and compares its value with its index:

  • Index 0: arr[0] = 9, 9 ? 0
  • Index 1: arr[1] = 2, 2 ? 1
  • Index 2: arr[2] = 1, 1 ? 2
  • Index 3: arr[3] = 3, 3 = 3 ? (first match found)

Alternative Approach Using findIndex()

We can also solve this using the built-in findIndex() method:

const arr = [9, 2, 1, 3, 6, 5];
const findFirstSimilarAlt = (arr = []) => {
   return arr.findIndex((element, index) => element === index);
};
console.log(findFirstSimilarAlt(arr));
3

Testing with Different Arrays

// Array with match at index 0
const arr1 = [0, 5, 2, 8];
console.log("Array [0, 5, 2, 8]:", findFirstSimilar(arr1));

// Array with no matches
const arr2 = [5, 8, 9, 2];
console.log("Array [5, 8, 9, 2]:", findFirstSimilar(arr2));

// Array with multiple matches
const arr3 = [0, 1, 8, 3, 4];
console.log("Array [0, 1, 8, 3, 4]:", findFirstSimilar(arr3));
Array [0, 5, 2, 8]: 0
Array [5, 8, 9, 2]: undefined
Array [0, 1, 8, 3, 4]: 0

Comparison

Method Readability Performance Early Exit
for loop Good Fast Yes
findIndex() Excellent Fast Yes

Conclusion

Both approaches efficiently find the first number that equals its index. The for loop provides explicit control, while findIndex() offers cleaner, more functional code. Both methods return undefined when no match is found.

Updated on: 2026-03-15T23:19:00+05:30

168 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements