- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Returning the nth even number using JavaScript
- Returning only odd number from array in JavaScript
- Finding the index of the first element that violates the series (first non-consecutive number) in JavaScript
- Returning the highest value from an array in JavaScript
- Returning array values that are not odd in JavaScript
- Returning reverse array of integers using JavaScript
- Return the first duplicate number from an array in JavaScript
- Splitting an array based on its first value - JavaScript
- Finding the first non-consecutive number in an array in JavaScript
- Returning an array with the minimum and maximum elements JavaScript
- Returning a decimal that have 1s in its binary form only at indices specified by array in JavaScript
- Get the first and last item in an array using JavaScript?
- Returning an array in Java
- Returning just greater array in JavaScript
- Returning an array containing last n even numbers from input array in JavaScript

Advertisements