Skip to content

Instantly share code, notes, and snippets.

@sakshstore
Created August 10, 2023 03:38
Show Gist options
  • Save sakshstore/3661d01fa969650ed5345f2f539d82e3 to your computer and use it in GitHub Desktop.
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.
// 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