Skip to main content

JavaScript Array Search

By SamK
0
0 recommends
Category(s)
Topic(s)

JavaScript provides several methods to search for elements in an array. Here are some commonly used methods:

indexOf() Method

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

Syntax

array.indexOf(item, start)
  • item (Required) – The element to search for.
  • start (Optional) – The index to start searching from.
  • If the element appears multiple times, it returns the index of its first occurrence.

Note: The index starts from 0, so the first element has an index of 0, the second 1, and so on.

Example

let arr = [10, 20, 30, 40];
console.log(arr.indexOf(30)); // Output: 2

lastIndexOf() Method

The lastIndexOf() method works like indexOf(), but it returns the last occurrence of an item.

Syntax

array.lastIndexOf(item, start)

Searches from start index backward to the beginning of the array.

Example

let fruits = ["apple", "banana", "cherry", "banana", "orange"];

console.log(fruits.lastIndexOf("banana")); // Output: 3 (last occurrence)
console.log(fruits.lastIndexOf("grape"));  // Output: -1 (not found)

includes() Method

The includes() method checks if an array contains a specific value, returning true or false.

Syntax

array.includes(item)

Unlike indexOf(), it correctly detects NaN values.

Example

let arr = [10, 20, 30, 40];
console.log(arr.includes(20)); // Output: true

find() Method

The find() method returns the first element that meets a condition.

Syntax

array.find(callback)
  • callback should return true for the desired condition.
  • Returns undefined if no element matches.

Example

let arr = [10, 20, 30, 40];
let result = arr.find(num => num > 25);
console.log(result); // Output: 30 (Which is > 25)

findIndex() Method

The findIndex() method works like find(), but it returns the index instead of the value.

Example

let arr = [10, 20, 30, 40];
console.log(arr.findIndex(num => num > 25)); // Output: 2

findLast() Method

The findLast() method returns the last element in an array that satisfies a given condition. If no element meets the condition, it returns undefined.

Syntax

array.findLast(callback(element, index, array))

Example

let numbers = [3, 7, 10, 15, 18, 21];
let lastEven = numbers.findLast(num => num % 2 === 0);
console.log(lastEven); // Output: 18

findLastIndex() Method

The findLastIndex() method returns the index of the last element in an array that satisfies a given condition. If no element meets the condition, it returns -1.

Example

let numbers = [3, 7, 10, 15, 18, 21];
let lastEvenIndex = numbers.findLastIndex(num => num % 2 === 0);
console.log(lastEvenIndex); // Output: 4

filter() Method

Returns an array of all elements that satisfy a condition.

let arr = [10, 20, 30, 40];
let filteredArr = arr.filter(num => num > 20);
console.log(filteredArr); // Output: [30, 40]

Questions & Answers