JavaScript Array Search
Searching arrays in JavaScript can be done using various methods. Here are a few commonly used ones:
- Array indexOf()
- Array lastIndexOf()
- Array includes()
- Array find()
- Array findIndex()
- Array findLast()
- Array findLastIndex()
In JavaScript, there are several methods you can use to search for elements in an array:
Array indexOf()
Returns the first index at which a given element can be found in the array, or -1 if it is not present.
Example
let arr = [1, 2, 3, 4, 5]; let index = arr.indexOf(3); // index is 2
Array lastIndexOf()
Returns the last index at which a given element can be found in the array, or -1 if it is not present. Searches the array from right to left.
Example
let arr = [1, 2, 3, 4, 3, 5]; let index = arr.lastIndexOf(3); // index is 4
Array includes()
Determines whether an array includes a certain element, returning true or false as appropriate.
Example
let arr = [1, 2, 3, 4, 5]; let isIncluded = arr.includes(3); // isIncluded is true
Array find()
Returns the first element in the array that satisfies the provided testing function. Otherwise, it returns undefined.
Example
let arr = [1, 2, 3, 4, 5]; let element = arr.find(x => x > 3); // element is 4
Array findIndex()
Returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1.
Example
let arr = [1, 2, 3, 4, 5]; let index = arr.findIndex(x => x > 3); // index is 3
Array findLast()
findLast() method that will start from the end of an array and return the value of the first element that satisfies a condition.
Example
const temp = [27, 28, 30, 40, 42, 35, 30]; let high = temp.findLast(x => x > 40);
Array findLastIndex()
The findLastIndex() method finds the index of the last element that satisfies a condition.