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 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
#web-development #javascript #programming #developer