Clue Mediator

How to search an array in JavaScript

📅February 5, 2022

Today you will learn how to search an array in JavaScript. Here, we will discuss four different methods to search for an item in an array using JavaScript.

Checkout more articles on JavaScript

Way to search an array in JavaScript

  1. Filter
  2. Find
  3. Includes
  4. IndexOf

1. Filter

The `Array.filter()` method creates a new array with all elements that pass the test implemented by the provided function.

const numbers = [22, 11, 33, 15, 25];
const newNumbers = numbers.filter(n => n > 20);
console.log(newNumbers);
// Output: [22, 33, 25]

2. Find

The `Array.find()` method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, `undefined` is returned.

const numbers = [22, 11, 33, 15, 25];
const newNumber = numbers.find(n => n > 20);
console.log(newNumber);
// Output: 22

3. Includes

The `Array.includes()` method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate.

const numbers = [22, 11, 33, 15, 25];
const isExist = numbers.includes(22);
console.log(isExist);
// Output: true

4. IndexOf

The `Array.indexOf()` method returns the first index at which a given element can be found in the array, or `-1` if it is not present.

const numbers = [22, 11, 33, 15, 25];
const index = numbers.indexOf(33);
console.log(index);
// Output: 2

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂