JavaScript Array Search
Array search methods help you find elements and their positions. Whether you need to check if an item exists, find its index, or locate elements matching certain conditions, these methods are essential.
Key Topics
indexOf() and lastIndexOf()
indexOf()
returns the first index of an element, and lastIndexOf()
returns its last occurrence.
let arr = ["A", "B", "A", "C"];
console.log(arr.indexOf("A"));
console.log(arr.lastIndexOf("A"));
Output
> 0
> 2
Explanation: The first "A" is at index 0, and the last "A" is at index 2.
includes()
includes()
checks if an array contains a specified element, returning true or false.
console.log(arr.includes("B"));
console.log(arr.includes("D"));
Output
> true
> false
Explanation: "B" exists in the array, but "D" does not, resulting in true and false respectively.
find() and findIndex()
find()
returns the first element that meets a condition, and findIndex()
returns the index of that element.
let nums = [10, 20, 30, 40];
let found = nums.find(n => n > 25);
let foundIndex = nums.findIndex(n => n > 25);
console.log(found);
console.log(foundIndex);
Output
> 30
> 2
Explanation: The first number greater than 25 is 30 at index 2. find()
returns the value, and findIndex()
returns the position.
JavaScript Usage in DOM
This DOM-based example uses array search methods to verify user input or find items before displaying results.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Search in DOM</title>
</head>
<body>
<h1>Array Search Demo</h1>
<input type="text" id="itemInput" placeholder="Search item">
<button onclick="searchItem()">Search</button>
<p id="result"></p>
<script>
let items = ["Pen", "Pencil", "Eraser"];
function searchItem() {
let input = document.getElementById("itemInput").value;
if (items.includes(input)) {
document.getElementById("result").textContent = input + " found.";
} else {
document.getElementById("result").textContent = input + " not found.";
}
}
</script>
</body>
</html>
Key Takeaways
- indexOf()/lastIndexOf(): Find positions of elements.
- includes(): Check if the array contains an element.
- find()/findIndex(): Locate elements based on conditions.
- DOM Integration: Validate and display search results dynamically.