Created
August 10, 2023 03:38
-
-
Save sakshstore/3661d01fa969650ed5345f2f539d82e3 to your computer and use it in GitHub Desktop.
The Array.find() and Array.findIndex() methods allow you to find elements in an array based on a condition.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Longhand | |
const numbers = [1, 2, 3, 4, 5]; | |
let foundNumber; | |
for (let i = 0; i < numbers.length; i++) { | |
if (numbers[i] > 3) { | |
foundNumber = numbers[i]; | |
break; | |
} | |
} | |
// Shorthand | |
const numbers = [1, 2, 3, 4, 5]; | |
const foundNumber = numbers.find((number) => number > 3); | |
const foundIndex = numbers.findIndex((number) => number > 3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment