JavaScript : Array Search

In JavaScript, you can search for elements in an array using various methods. Here are some common techniques for searching arrays:

1. indexOf()


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


let fruits = ['apple', 'banana', 'orange', 'grape'];
console.log(fruits.indexOf('orange')); // Output: 2
console.log(fruits.indexOf('pear'));   // Output: -1

 

2. lastIndexOf()


The lastIndexOf() method returns the index of the last occurrence of a specified element in an array. If the element is not found, it returns -1.


let fruits = ['apple', 'banana', 'orange', 'banana', 'grape'];
console.log(fruits.lastIndexOf('banana')); // Output: 3
console.log(fruits.lastIndexOf('pear'));   // Output: -1

 

3. find()


The find() method returns the first element in an array that satisfies a provided testing function. If no such element is found, it returns undefined.


let numbers = [1, 2, 3, 4, 5];
let evenNumber = numbers.find(num => num % 2 === 0);
console.log(evenNumber); // Output: 2

 

4. findIndex()


The findIndex() method returns the index of the first element in an array that satisfies a provided testing function. If no such element is found, it returns -1.


let numbers = [1, 2, 3, 4, 5];
let index = numbers.findIndex(num => num % 2 === 0);
console.log(index); // Output: 1

 

5. includes()


The includes() method determines whether an array includes a certain element, returning true or false as appropriate.


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

 

These methods provide different ways to search for elements in arrays based on various criteria. Depending on your specific requirements, you can choose the appropriate method or combination of methods to perform array searching efficiently.