JS Array Search

JavaScript Array Search Methods

JavaScript provides several powerful methods to search for elements within an array. These methods help you find the position of an element, check for its existence, or find an element that matches a specific condition.


1. indexOf() and lastIndexOf()

indexOf() and lastIndexOf() Example

const fruits = ["Apple", "Orange", "Apple", "Mango"];

let firstIndex = fruits.indexOf("Apple"); let lastIndex = fruits.lastIndexOf("Apple");

console.log(firstIndex); // 0 console.log(lastIndex); // 2


2. includes()

The includes() method determines whether an array includes a certain value, returning true or false as appropriate. This is often a more readable way to check for an element's existence than using indexOf().

includes() Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];

let hasApple = fruits.includes("Apple"); let hasKiwi = fruits.includes("Kiwi");

console.log(hasApple); // true console.log(hasKiwi); // false


3. find()

The find() method returns the value of the first element in an array that passes a test (provided as a callback function). If no values satisfy the testing function, undefined is returned.

find() Example

const numbers = [4, 9, 16, 25, 29];

// Find the first number greater than 18 let first = numbers.find(myFunction);

function myFunction(value, index, array) { return value > 18; }

console.log(first); // 25


4. findIndex()

The findIndex() method is similar to find(), but it returns the index of the first element that passes the test. If no element passes the test, it returns -1.

findIndex() Example

const numbers = [4, 9, 16, 25, 29];

// Find the index of the first number greater than 18 let firstIndex = numbers.findIndex(value => value > 18);

console.log(firstIndex); // 3


Exercise

?

Which method would you use to check if an array contains the value "apple" and get a simple `true` or `false` result?