HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Array Search

Written by RedoHub Team

JavaScript provides several methods to search through an array. Some methods allow you to look for a specific value, while others allow you to find items that match a certain condition.


Basic Search Methods

These methods are used when you have a specific value in mind (like a number or string) and you want to know if or where it exists in the array.

1. indexOf() and lastIndexOf()

Returns the position of the first (or last) occurrence of a value. Returns -1 if the value is not found.

const fruits = ["Apple", "Orange", "Apple", "Mango"];
console.log(fruits.indexOf("Apple"));     // 0
console.log(fruits.lastIndexOf("Apple")); // 2

2. includes()

Returns true if the array contains the specified value, false otherwise. This is often cleaner than checking indexOf !== -1.

const colors = ["Red", "Green", "Blue"];
console.log(colors.includes("Green")); // true

Advanced Searching with Conditions

Sometimes you need to find an item not by its value, but by a test. For example, finding the first number greater than 10.

1. find()

The find() method returns the value of the first array element that passes a test function.

const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);

function myFunction(value) {
  return value > 18;
}
console.log(first); // 25

2. findIndex()

Similar to find(), but returns the index of the first element that passes the test, instead of its value.

const numbers = [4, 9, 16, 25, 29];
let index = numbers.findIndex(x => x > 18); // Using arrow function
console.log(index); // 3

ES2023 Search Methods

Newer versions of JavaScript introduced methods to search an array starting from the end:

  • findLast() — Returns the value of the last matching element.
  • findLastIndex() — Returns the index of the last matching element.

Key Points to Remember

  • Use indexOf() if you need the position of a primitive value
  • Use includes() to simply check for existence
  • Use find() when looking for an object or matching a condition
  • All these methods are sequential: they stop as soon as they find a match
  • The Callback function for find receives three arguments: value, index, and the array itself