Efficiently Searching an Element in an Array
Learn how to quickly find an element in an array using linear and binary search methods. The linear search scans each element, while the binary search is faster for sorted arrays, dividing the search space into half with each step.
Table of Contents
1. indexOf()
The function searches for the first occurrence of a specified value in an array and returns its index. If the value is not found, the function returns -1.
//index [0, 1, 2, 3, 4]
const numbers = [2, 9, 13, 5, 7];
const index = numbers.indexOf(13);
// Outputs: 2
If the value doesn’t exist in the array:
const numbers = [2, 9, 13, 5, 7];
const notFound = numbers.indexOf(42);
console.log(notFound);
// Output: -1
2. includes()
The function checks whether an array contains a specific value and returns true if it is found, and false if it is not.
const cars = ['BMW', 'Audi', 'Mercedes'];
const hasMercedes = cars.includes('Mercedes');
console.log(hasMercedes);
// Outputs: true
3. find()
The function returns the first element in the array that satisfies the condition defined in the provided testing function. If no element meets the condition, the function returns undefined.
const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(element => element > 10);
console.log(found);
// Output: 12
4. findIndex()
The function returns the index of the first element in the array that satisfies the condition defined by the provided testing function. If no element meets the condition, the function returns -1.
const numbers = [5, 12, 8, 130, 44];
const index = numbers.findIndex(element => element > 10);
console.log(index);
// Output: 1
If no match is found:
const numbers = [5, 12, 8, 130, 44];
const notFound = numbers.findIndex(element => element > 200);
console.log(notFound);
// Output: -1
5. filter()
The function returns a new array containing all elements that satisfy the condition defined by the provided testing function.
const numbers = [5, 12, 8, 130, 44];
const filtered = numbers.filter(element => element > 10);
console.log(filtered);
// Output: [12, 130, 44]