To filter a list with multiple fields, you need to apply both filters simultaneously. Here's an example of how you can achieve this but before that i want to explain the process step by step:
Set up your filter options:
- Create two states to store the selected work and city filters.
- Update these states whenever the user selects a filter option.
Apply the filters to your list:
On event handler Iterate over the list of data.
Check if each item matches the selected work and city filters.
Only display the items that satisfy both conditions.
Here's a code to in js that will illustrate the concept, and if you need to understand the concept in pure react visit the codesandbox url :
The data that will used in the example is this:
const data = [
{ id: 0, name: "Abidullah", work: "Developer", city: "New York" },
{ id: 1, name: "John Doe", work: "Developer", city: "New York" },
{ id: 2, name: "Adam", work: "Designer", city: "New York" },
{ id: 3, name: "Jane Smith", work: "Designer", city: "Los Angeles" },
{ id: 4, name: "Mark Johnson", work: "Developer", city: "San Francisco" },
{ id: 5, name: "Alam", work: "HR", city: "Karachi" }
];
Step 1: Set up filter options
let selectedWork = '';
let selectedCity = '';
Note: Update the selectedWork and selectedCity variables based on user input or events.
Step 2: Apply filters to the data
const filteredData = data.filter(item => {
// If both work and city filters are selected, apply both filters
if (selectedWork && selectedCity) {
return item.work === selectedWork && item.city === selectedCity;
}
// If only work filter is selected, apply work filter
else if (selectedWork) {
return item.work === selectedWork;
}
// If only city filter is selected, apply city filter
else if (selectedCity) {
return item.city === selectedCity;
}
// If no filters are selected, return all items
else {
return true;
}
});
Finally use the filteredData for display or further processing.
Here is the complete Example:
const data = [
{ id: 0, name: "Abidullah", work: "Developer", city: "New York" },
{ id: 1, name: "John Doe", work: "Developer", city: "New York" },
{ id: 2, name: "Adam", work: "Designer", city: "New York" },
{ id: 3, name: "Jane Smith", work: "Designer", city: "Los Angeles" },
{ id: 4, name: "Mark Johnson", work: "Developer", city: "San Francisco" },
{ id: 5, name: "Alam", work: "HR", city: "Chicago" }
];
let selectedWork = 'Developer';
let selectedCity = 'New York';
const filteredData = data.filter(item => {
if (selectedWork && selectedCity) {
return item.work === selectedWork && item.city === selectedCity;
}
else if (selectedWork) {
return item.work === selectedWork;
}
else if (selectedCity) {
return item.city === selectedCity;
}
else {
return true;
}
});
console.log(filteredData)