I have two dropdowns which function as filters for job postings.
const type = ['all', 'fulltime', 'parttime']; const department = ['all', 'engineering', 'design'];
Here is the data I’m trying to filter (by default both the dropdowns have a value of all)
let jobs = [
{
role: 'a',
department: 'engineering',
type: 'fulltime'
},
{
role: 'b',
department: 'design',
type: 'parttime'
},
{
role: 'c',
department: 'engineering',
type: 'parttime'
}
]
Both filters can be active at the same time, thus filtering two-levels.
eg: Department Filter Selected: ‘Engineering’ ([2] returns array of 2 objects) => user selects second filter => Type Filter Selected: ‘fulltime’ ([1] returns array of 1 object)
All clicking all of a filter, it should reset that particular filter only.
Here is what I tried, can’t seem to wrap my head around a reasonable solution.
const filterJobs = () => {
const { department, type} = filters; //filters selected by user
if(department === 'all'){
return;
} else{
filteredJobs = jobs.filter((job)=>job.department === department)
}
if(type === 'all'){
return;
} else{
filteredJobs = jobs.filter((job)=>job.type === type)
}
}
Thanks in advance!
Advertisement
Answer
Use just a single .filter, and in the callback, perform both checks for department and type in separate expressions:
jobs.filter((job) => ( (department === 'all' || job.department === department) && (type === 'all' || job.type === type) ));