Arrays are fundamental data structures in JavaScript, used to store ordered collections of elements. Searching them efficiently is crucial for various programming tasks. This chapter delves into the built-in methods and advanced techniques for finding elements within arrays.
indexOf()
:
const colors = ["red", "green", "blue", "red"];
const index = colors.indexOf("green"); // index will be 1
Output: The output for the above code is 1
.
lastIndexOf()
:indexOf()
, but returns the last index of the matching element.
const colors = ["red", "green", "blue", "red"];
const lastIndex = colors.lastIndexOf("red"); // lastIndex will be 3
Output: The output for the above code is 3
.
includes()
:true
if found, false
otherwise.indexOf()
, uses strict equality.
const fruits = ["apple", "banana", "orange"];
const hasMango = fruits.includes("mango"); // hasMango will be false
Output: The output for the above code is false
.
find()
:undefined
if none matches.
const numbers = [10, 20, 30, 40];
const evenNumber = numbers.find(number => number % 2 === 0); // evenNumber will be 20
Output: The output for the above code is 20
.
findIndex()
:find()
, but returns the index of the first matching element instead of the value.
const names = ["Alice", "Bob", "Charlie"];
const charlieIndex = names.findIndex(name => name === "Charlie"); // charlieIndex will be 2
Output: The output for the above code is 2
.
filter()
:find()
, takes a callback function that determines which elements to include.
const products = [
{ name: "Shirt", price: 20 },
{ name: "Jeans", price: 40 },
{ name: "Hat", price: 15 }
];
const discountedProducts = products.filter(product => product.price < 30);
discountedProducts
array will contain objects with prices less than 30.for
or forEach
.
function findStudentsByMajor(students, major) {
const matchingStudents = [];
for (const student of students) {
if (student.major === major) {
matchingStudents.push(student);
}
}
return matchingStudents;
}
const csStudents = findStudentsByMajor(students, "CS");
console.log(csStudents); // Output: [{ name: "John", age: 20, major: "CS" }, { name: "Peter", age: 21, major: "CS" }]
This example demonstrates a custom function findStudentsByMajor
that iterates through the students
array and returns a new array containing only students with the specified major.
function findAdvancedStudents(students) {
return students.filter(student => student.age > 19 && student.major === "CS");
}
const advancedCSStudents = findAdvancedStudents(students);
console.log(advancedCSStudents); // Output: [{ name: "John", age: 20, major: "CS" }]
const inventory = [
["Shirt", 20],
["Jeans", 40],
["Hat", 15],
[["T-Shirt", 10], ["Jacket", 50]]
];
function findDiscountedItems(inventory) {
const discountedItems = [];
for (const item of inventory) {
if (Array.isArray(item)) {
discountedItems.push(...findDiscountedItems(item)); // Recursive call for nested arrays
} else if (item[1] < 20) { // Assuming price is at index 1
discountedItems.push(item);
}
}
return discountedItems;
}
const discountedProducts = findDiscountedItems(inventory);
console.log(discountedProducts); // Output: [["Shirt", 20], ["T-Shirt", 10]]
function findStudent(students, name, age) {
return students.find(student => student.name === name && student.age === age);
}
const targetStudent = findStudent(students, "John", 20);
console.log(targetStudent); // Output: { name: "John", age: 20, major: "CS" }
in
operator to check if a property exists in an object within an array.
function hasEmail(student) {
return "email" in student;
}
const studentsWithEmail = students.filter(hasEmail);
console.log(studentsWithEmail); // Output: (may vary depending on student data)
Promise.all()
or async/await
.
async function searchProducts(urls) {
const results = await Promise.all(urls.map(async url => {
const response = await fetch(url);
const data = await response.json();
return data;
}));
// Process the search results from each API call
}
const productURLs = ["api1.com/products", "api2.com/products"];
searchProducts(productURLs);
JavaScript provides a rich set of built-in methods and allows for custom approaches to search arrays. Choosing the appropriate method depends on the specific search criteria and array structure. This guide equips you with the knowledge to effectively search arrays in your JavaScript applications. By combining these techniques, you can handle even the most intricate search requirements. Happy coding !❤️