The Wayback Machine - https://web.archive.org/web/20240213201135/https://www.geeksforgeeks.org/best-way-to-find-an-item-in-an-array-in-javascript/
Open In App
Related Articles

Best Way to Find an Item in an Array in JavaScript

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In JavaScript, an array is a collection of elements that can hold different data types. There are various ways to check if a specific item is present in an array. In this article, we will see the possible techniques to find the item in a given array in JavaScript.

The most commonly used methods to find if an item is in a JavaScript array are:

Approach 1: Using the includes() method

The includes() method checks if an array includes a certain value, returning the boolean value true or false accordingly.

Syntax:

array.includes(value);

Example 1: In this example, we have an array of fruits containing three fruits. We use the includes() method to check if the banana is in the array, which returns true. We also check if grapes are in the array, which returns false.

Javascript

const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.includes('banana')); // Output: true
console.log(fruits.includes('grapes')); // Output: false

                    

Output
true
false

Example 2: In this example, the if-else statement is used to determine if ‘cat’ is in the array. If ‘cat’ is found in the array, the message “Cat is in the array!” will be printed on the console. If ‘cat’ is not found in the array, the message “Cat is not in the array.” will be printed instead.

Javascript

const animals = ['dog', 'cat', 'bird', 'rabbit'];
 
// Check if 'cat' is in the array using includes()
if (animals.includes('cat')) {
    console.log('Cat is present in the array!');
} else {
    console.log('Cat is not present in the array.');
};

                    

Output
Cat is present in the array!

Approach 2: Using the indexOf() method

The indexOf() method returns the index of the first occurrence of a specified value in an array, or -1 if it is not found.

Syntax:

array.indexOf(value);

Example 1: In this example, we have an array of fruits containing three fruits. We use the indexOf() method to check if the banana is in the array, which returns the index 1 (since the banana is the second element in the array). We also check if grapes are in the array, which returns -1 (since grapes are not found in the array).

Javascript

const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.indexOf('banana')); // Output: 1
console.log(fruits.indexOf('grapes')); // Output: -1

                    

Output
1
-1

Example 2: In this example, the indexOf() method is used to check if “hamster” is in the animal’s array. If the method returns -1, it means “hamster” is not in the array and the code will output “Hamster is not in the array.” If the method returns a value other than -1, it means “hamster” is in the array and the code will output “Hamster is in the array!”.

Javascript

const animals = ['dog', 'cat', 'bird', 'rabbit'];
 
// Check if 'hamster' is in the array using indexOf()
if (animals.indexOf('hamster') !== -1) {
    console.log('Hamster is in the array!');
} else {
    console.log('Hamster is not in the array.');
};

                    

Output
Hamster is not in the array.

Approach 3: Using the find() method

The find() method returns the value of the first element in an array that satisfies a provided testing function, or undefined if no values satisfy the function.

Syntax:

array.find(callback);

Parameter:

This method accepts the array as the name of the array and a callback denotes the testing function.

Example 1: In this example, The find() method is called on the fruits array and takes a callback function as its argument. The callback function takes each element of the array as its parameter and returns a boolean value indicating whether or not the element matches the desired criteria.

Javascript

const fruits = ['apple', 'banana', 'orange'];
const result = fruits.find(fruit => fruit === 'banana');
if (result) {
    console.log("banana is present in the array");
} else {
    console.log("banana is not present in the array");
};

                    

Output
banana is present in the array

Example 2: In this example, we have an array of people containing four objects, each representing a person with a name and an age. We use the find() method to search for the first object in the array that satisfies the provided testing function person => person.age > 30, which checks if the current person’s age is greater than 30.

Javascript

const people = [
    { name: 'John', age: 28 },
    { name: 'Jane', age: 32 },
    { name: 'Mary', age: 25 },
    { name: 'Mark', age: 36 },
];
 
// Find the first person in the array
// who is over 30 years old
const result = people.find(person => person.age > 30);
 
if (result) {
    console.log(`The first person over 30 is ${result.name}.`);
} else {
    console.log('No people over 30 found in the array.');
};

                    

Output
The first person over 30 is Jane.

Approach 4: Using Array.some() method

The some() method tests whether at least one element in the array passes the provided function

Syntax:

arr.some(callback(element,index,array),thisArg);

Example 1: In this example, the some() method checks if at least one element in the array is equal to the target item (3). If found, it returns true, indicating that the item exists in the array.

Javascript

// Array of numbers
const numbers = [1, 2, 3, 4, 5];
 
// Item to find
const target = 3;
 
// Using Array.some() to find the item
const isItemFound = numbers.some(item => item === target);
 
// Check if the item is found
if (isItemFound) {
  console.log(`${target} is found in the array.`);
} else {
  console.log(`${target} is not found in the array.`);
}

                    

Output
3 is found in the array.

Example 2: In this example, the some() method is used to check if there is at least one book in the array with the specified author ('Harper Lee'). The result is a boolean indicating whether the condition is met for at least one element in the array.

Javascript

// Array of objects representing books
const books = [
  { id: 1, title: 'The Catcher in the Rye', author: 'J.D. Salinger' },
  { id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee' },
  { id: 3, title: '1984', author: 'George Orwell' },
  { id: 4, title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
];
 
// Check if there is at least one book by a specific author
const targetAuthor = 'Harper Lee';
 
const hasBooksByAuthor = books.some(book => book.author === targetAuthor);
 
if (hasBooksByAuthor) {
  console.log(`There is at least one book by ${targetAuthor}.`);
} else {
  console.log(`No books found by ${targetAuthor}.`);
}

                    

Output
There is at least one book by Harper Lee.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!


Last Updated : 18 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials