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

JavascriptWeb DevelopmentFront End Technology

<h2>Problem</h2><p>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.</p><h2>Example</h2><p>Following is the code &minus;</p><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notransalte">const arr = [9, 2, 1, 3, 6, 5]; const findFirstSimilar = (arr = []) =&gt; { &nbsp; &nbsp;for(let i = 0; i &lt; arr.length; i++){ &nbsp; &nbsp; &nbsp; const el = arr[i]; &nbsp; &nbsp; &nbsp; if(el === i){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return i; &nbsp; &nbsp; &nbsp; }; &nbsp; &nbsp;}; }; console.log(findFirstSimilar(arr));</pre><h2>Output</h2><pre class="result notransalte">3</pre>
Updated on 20-Apr-2021 09:09:37