How to Search in JavaScript Array

How to Search in JavaScript Array? To find a specific item in an array, you can use a variety of techniques in JavaScript. Depending on your unique use case, you can choose any number of methods.

Do you want to get every item in an array that satisfies a specific condition, for instance? JavaScript’s Array.prototype methods have you covered for all of these usage scenarios. In this post, we’ll go through four different ways to look for a specific item in an array. These approaches are:-

  • filter() Method
  • find() Method

Search in JavaScript Array Using Array.filter()

To locate elements in an array that satisfy a specific requirement, we can use the Array.filter() method. For instance, we can follow these steps to get every item in an array of numbers that is greater than 10:

const array = [1, 2, 3, 43, 25];
const values = array.filter((element) => element > 10);
console.log(values);

Output:-

[ 43, 25 ]

The function is applied to each element of the array. An empty array is returned if none of the array’s items satisfy the requirement. Read more about this approach here.

Sometimes we only require some of the components that satisfy a particular requirement. We only have one ingredient to fulfill the criterion. You must then use the find() method.

Search in JavaScript Array Using Array.find()

To locate the first element that satisfies a requirement, we use the Array.find() method. It accepts a callback as an input, the same as the filter() function, and returns the first element that satisfies the callback requirement.

Let’s apply the find() method to the array from the previous example:-

const array = [1, 3, 67, 20, 8];
const greaterThanTen = array.find((element) => element > 10);
console.log(greaterThanTen);

Output:-

67

Each value in the array is subject to the callback function, which has three arguments:-

  • element is the subject of the iteration (required)
  • index: The current element’s location or index (optional)
  • array – the array on which we executed the search (optional)

But keep in mind that it returns undefined if none of the elements in the array satisfy the requirement. Also see:- Get Random Element From Array in JavaScript

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *