JavaScript Array Search
8 April 2025 | Category: JavaScript
In JavaScript, you can search through arrays to find values, check if an item exists, or get its position.
JavaScript provides multiple methods to help you search arrays easily and effectively.
✅ 1. indexOf()
– Find the First Index
The indexOf()
method returns the index of the first occurrence of a value.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.indexOf("Banana")); // 1
console.log(fruits.indexOf("Orange")); // -1 (not found)
🔹 If the value is not found, it returns
-1
.
✅ 2. lastIndexOf()
– Find the Last Index
The lastIndexOf()
method returns the last occurrence of a value.
let nums = [1, 2, 3, 2, 4, 2];
console.log(nums.lastIndexOf(2)); // 5
✅ 3. includes()
– Check if Value Exists
The includes()
method checks whether a specific value is present in the array.
let colors = ["Red", "Green", "Blue"];
console.log(colors.includes("Green")); // true
console.log(colors.includes("Yellow")); // false
✅ 4. find()
– Find First Matching Element
The find()
method returns the first item that satisfies a condition (callback function).
let ages = [14, 18, 21, 16];
let adult = ages.find(age => age >= 18);
console.log(adult); // 18
🔹 It returns
undefined
if no match is found.
✅ 5. findIndex()
– Find Index of First Match
Returns the index of the first element that satisfies a condition.
let nums = [5, 10, 15, 20];
let index = nums.findIndex(num => num > 10);
console.log(index); // 2
✅ 6. filter()
– Find All Matching Elements
Returns a new array containing all elements that match a condition.
let scores = [80, 45, 90, 70, 50];
let passed = scores.filter(score => score >= 60);
console.log(passed); // [80, 90, 70]
📌 Quick Comparison Table
Method | Returns | Use Case |
---|---|---|
indexOf() | Index (first match) | Find position of a value |
lastIndexOf() | Index (last match) | Find last occurrence |
includes() | true / false | Check if value exists |
find() | First matching value | Get value based on condition |
findIndex() | Index of first match | Get index based on condition |
filter() | Array of matching values | Get all values that match |
🧠 Summary
- Use
indexOf()
/lastIndexOf()
for exact value searches. - Use
includes()
for simple existence checks. - Use
find()
andfindIndex()
when working with conditions. - Use
filter()
to get all values that match a condition.