Js Array Search in JavaScript
? JavaScript Array Search Methods
JavaScript offers several built-in methods to search for values or elements inside arrays.
Common Array Search Methods
| Method | Description | Example | Returns |
|---|---|---|---|
.indexOf(value) | Returns the index of the first occurrence of value, or -1 if not found | [1,2,3].indexOf(2) ? 1 | Number (index) |
.lastIndexOf(value) | Returns the index of the last occurrence of value, or -1 if not found | [1,2,3,2].lastIndexOf(2) ? 3 | Number (index) |
.includes(value) | Checks if array contains the value (boolean) | [1,2,3].includes(2) ? true | Boolean |
.find(callback) | Returns the first element that satisfies the callback condition | [1,2,3].find(x => x > 1) ? 2 | Element or undefined |
.findIndex(callback) | Returns the index of the first element that satisfies the condition, or -1 | [1,2,3].findIndex(x => x > 2) ? 2 | Number (index) |
.filter(callback) | Returns a new array with all elements passing the test | [1,2,3,4].filter(x => x > 2) ? [3,4] | New Array |
Examples
const numbers = [10, 20, 30, 20, 40];// indexOfconsole.log(numbers.indexOf(20)); // 1console.log(numbers.indexOf(50)); // -1 (not found)// lastIndexOfconsole.log(numbers.lastIndexOf(20)); // 3// includesconsole.log(numbers.includes(30)); // trueconsole.log(numbers.includes(50)); // false// find (first number greater than 25)const found = numbers.find(num => num > 25);console.log(found); // 30// findIndex (index of first number divisible by 4)const foundIndex = numbers.findIndex(num => num % 4 === 0);console.log(foundIndex); // 1 (20 is divisible by 4)// filter (all numbers > 15)const filtered = numbers.filter(num => num > 15);console.log(filtered); // [20, 30, 20, 40]Quick Tips
Use
.indexOf()or.includes()for simple exact value searches.Use
.find()or.findIndex()for more complex conditions with callbacks.Use
.filter()if you want all matching elements instead of just the first.
Want me to show how to search in arrays of objects or how to do case-insensitive searches?