Searching is one of the most common features users expect in any application โ whether itโs a product search on an e-commerce site, filtering contacts, or real-time search suggestions. In this article, weโll explore how to build search functionality in JavaScript and look at real-life examples to make it practical and relevant.
โ What You'll Learn
- - The basics of implementing search in JavaScript
- - Case-insensitive and fuzzy matching
- - Real-world examples: e-commerce, contact apps, todo lists
- - Performance tips for large datasets
Understanding the Basics
Search functionality typically involves:
- A data source (array of objects)
- A search input field
- A filter or search algorithm
- Rendering the filtered results
- Letโs see it in action
Real-Life Use Case #1: E-commerce Product Search
Imagine you have a JSON list of products, and you want users to find matches by title, category, or brand.
const products = [
{ title: "Nike Running Shoes", category: "Footwear", brand: "Nike" },
{ title: "Apple iPhone 14", category: "Electronics", brand: "Apple" },
{ title: "Leather Wallet", category: "Accessories", brand: "Fossil" },
];
function searchProducts(query) {
query = query.toLowerCase();
return products.filter(product =>
product.title.toLowerCase().includes(query) ||
product.category.toLowerCase().includes(query) ||
product.brand.toLowerCase().includes(query)
);
}
Real-Life Use Case #2: Searching Contacts in a Web App
const contacts = [
{ name: "Ankit Chaurasiya", email: "ankit@example.com" },
{ name: "John Doe", email: "john@example.com" },
];
function searchContacts(query) {
return contacts.filter(
c =>
c.name.toLowerCase().includes(query.toLowerCase()) ||
c.email.toLowerCase().includes(query.toLowerCase())
);
}
๐ Real-Life Use Case #3: Searching Tasks in a Todo App
const todos = [
{ task: "Buy groceries", completed: false },
{ task: "Finish project report", completed: true },
{ task: "Schedule team meeting", completed: false },
];
function searchTodos(query) {
return todos.filter(todo =>
todo.task.toLowerCase().includes(query.toLowerCase())
);
}
Top comments (2)
there is a CLI named BeB you can use it to create a backend experss and mongodb project in one line try it ๐
ok Nice, Its working fine.
you can try also mine. a sast-scan node package