User Tools

Site Tools


java-script:find-and-find-index-methods

Java Script Find / Find Index methods

Unlike filter method that returns all the matching elements, find and findIndex will stop at the first matching element found.

Find

The find method returns the first element in an array that satisfies a given test function. If no elements satisfy the test, it returns undefined.

const numbers = [10, 20, 30, 40];
const found = numbers.find(number => number > 20);
console.log(found); // 30

Find index

The findIndex method returns the index of the first element in an array that satisfies a given test function. If no elements satisfy the test, it returns -1.

const numbers = [10, 20, 30, 40];
const index = numbers.findIndex(number => number > 20);
console.log(index); // 2

Summary

  • Use find when you want to retrieve the first item that satisfies a condition.
  • Use findIndex when you need the index of the first item that satisfies a condition.
  • Use filter when you need all items that satisfy a condition.
java-script/find-and-find-index-methods.txt · Last modified: 2023/08/11 16:47 by odefta