Machine Coding · Lesson 6 of 12 · 3 min
Filtering & Searching Data
This is a fundamental skill. If you can't filter a list and debounce a search input correctly, you won't pass the interview.
When to filter on the client vs. the server
This is the first question you should ask, silently or aloud. The answer depends entirely on the size of the dataset.
- Client-side: If the total dataset is small (a few hundred, maybe up to 2,000 items), fetch it all at once and perform filtering and searching in the browser. It's faster for the user, as there are no network round-trips for each interaction. This is the most common scenario in machine coding interviews.
- Server-side: For anything larger, the client-side approach will fail. Sending a massive JSON payload is slow, and running searches on thousands of items can freeze the UI. For large datasets, the client should only send filter/search parameters to an API and display the results returned by the server.
In an interview, clarify the expected data size. Stating your assumption ("Assuming the dataset is small enough for client-side filtering...") shows you're thinking about scale, which is a senior trait.
How to combine filtering and searching
Filtering and searching are distinct. Filtering reduces the dataset based on discrete options (e.g., category dropdowns, status checkboxes). Searching scans for a free-text query within the data.
When you have both, the order of operations matters for performance. Always filter first, then search.
- Start with the full dataset.
- Apply filters (e.g.,
category === 'Electronics'). This creates a smaller, intermediate array. - Apply the search query only to this smaller array.
Searching a pre-filtered list of 50 items is much faster than searching the original 5,000. This becomes critical as you add more filters.
Why you must debounce search inputs
A naive implementation triggers a search on every keystroke. For a term like "laptop", you'd re-filter the entire list six times. This is inefficient and can make the UI feel sluggish.
Debouncing solves this by waiting for the user to pause typing before executing the search. A delay of 200-500ms is typical.
The trap: A common mistake is implementing a debounce with setTimeout but forgetting to clear the previous timer. This creates a cascade of timers, defeating the purpose of the debounce and potentially causing bugs. The cleanup function in a useEffect hook is the correct way to handle this.
Putting it all together
Here is a complete, production-grade example in React. It combines a category filter with a debounced search input. Pay close attention to the useMemo hook; it ensures the expensive filtering logic only re-runs when the dependencies—the selected category or the debounced search term—actually change.
import React, { useState, useEffect, useMemo } from 'react';
// Assume 'allProducts' is an array of product objects available in this scope.
// interface Product { id: number; name: string; category: string; }
function ProductList({ allProducts }) {
const [selectedCategory, setSelectedCategory] = useState('All');
const [searchTerm, setSearchTerm] = useState('');
const [debouncedSearchTerm, setDebouncedSearchTerm] = useState('');
// 1. Debounce the user's search input
useEffect(() => {
const timerId = setTimeout(() => {
setDebouncedSearchTerm(searchTerm);
}, 300);
// Cleanup function to clear the timer on every keystroke
return () => {
clearTimeout(timerId);
};
}, [searchTerm]);
// 2. Memoize the filtering and searching logic
const filteredProducts = useMemo(() => {
let products = allProducts;
// First, apply the category filter
if (selectedCategory !== 'All') {
products = products.filter(p => p.category === selectedCategory);
}
// Then, apply the debounced search term on the filtered list
if (debouncedSearchTerm) {
const lowercasedTerm = debouncedSearchTerm.toLowerCase();
products = products.filter(p =>
p.name.toLowerCase().includes(lowercasedTerm)
);
}
return products;
}, [selectedCategory, debouncedSearchTerm, allProducts]); // Re-run only when these change
return (
<div>
<select onChange={(e) => setSelectedCategory(e.target.value)} value={selectedCategory}>
{/* Options for categories */}
</select>
<input
type="text"
placeholder="Search..."
onChange={(e) => setSearchTerm(e.target.value)}
value={searchTerm}
/>
<ul>
{filteredProducts.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
}
How to show you're a senior candidate
The code above is what's expected. To exceed expectations, be ready to discuss how you would improve it.
Interviewer: "This is great. How would you scale this if we had 50,000 products?"
You: "For 50,000 products, client-side filtering is no longer viable. We'd move this logic to the server. The
selectedCategoryanddebouncedSearchTermwould become query parameters in an API call, like/api/products?category=Electronics&q=laptop. The component would manage loading and error states for that network request. I'd also ensure the URL updates with these parameters so users can share links to filtered views."
Other talking points:
- Accessibility: Announce the number of results using an
aria-liveregion so screen reader users know the list has updated. - Better search: For more than basic
string.includes(), you could use a client-side fuzzy search library like Fuse.js or discuss server-side search indexing with tools like Elasticsearch.
Try it
Implement a filterable list for our platform's /problems/ page. Fetch the list of problems and add two controls: a multi-select dropdown to filter by difficulty (Easy, Medium, Hard) and a debounced text input to search by problem title.
Next: Now that you can filter data, you need to handle displaying large result sets. We'll cover that in Pagination & Infinite Scroll.
Lock it in — apply this lesson under interview conditions.