There are various methods available to find elements or their positions in Array. But we can always choose the method that satisfies our search criteria i.e. whether we are searching for element or its position in the array.

We will be discussing about 6 ways to find in array. The various methods are find, findIndex, includes, indexOf, lastIndexOf and loops (for, filter, map). Let’s check them out in brief.

  • The find() method
  • The findIndex() method
  • The includes() method
  • The indexOf() method
  • The lastIndexOf method
  • Looping through Array elements and find
    • Using for loop
    • Using map() method
    • Using filter() method

The find() method

The Array find() method returns the first matched element in array that satisfies a condition. The find() method takes a function as argument which returns true or false based on some condition. The find() method executes this function for each element of array. If the function returns true for any element then that element will be returned by the find() method and it stops checking further for rest of the elements. If no element passed the condition then find() method will return undefined.

let score = [55, 73, 82, 66, 48];

let value = score.find(val => val > 60);
// returns the first element that passed the condition

console.log(value); // 73

The findIndex() method

The Array findIndex() method returns the index of first matched element in array that satisfies a condition. This method also takes a function argument which returns true or false.

The findIndex() method works the same way as find() method except find() returns the first matched element and findIndex() returns the index of the first matched element. If no match found in the array then findIndex() returns -1.

let score = [55, 73, 82, 66, 48];

let index = score.findIndex(val => val > 60);
// returns the index of first element that passed the condition

console.log(index); // 1

#javascript #programming #developer

6 Ways to Find Elements in JavaScript Array
2.00 GEEK