I have a list of subjects and need to filter it based on the filter selection
let subjects = [
{
"id": "course 1",
"title": "course 1",
"area": ["red"," blue"],
"mode": "offline",
"available": "full-time | part-time",
},
{
"id": "course 2",
"title": "course 3",
"area": ["red"],
"mode": "online",
"available": "part-time",
},
{
"id": "course 2",
"title": "course 3",
"area": ["blue", "green"],
"mode": "offline",
"available": "full-time | part-time",
},
]
There are 3 filters(area, mode, available) where the user can select multiple options from each filter
For example, after user selection my filter object looks like (it can be empty if none of the options are chosen from filters, here I have not chosen any options from filter2)
let filters = { filter1: ["red", "green"], filter2: "" , filter3: ["full-time"]}
Expected output
Based on the filters selected, I need to display the subjects that has
subjects.area
as red or green or bothsubjects.available
as full-time
let subjects = [
{
"id": "course 1",
"title": "course 1",
"area": ["red"," blue"],
"mode": "offline",
"available": "full-time | part-time",
},
{
"id": "course 2",
"title": "course 3",
"area": ["blue", "green"],
"mode": "offline",
"available": "full-time | part-time",
},
]
Things I tried
- I tried using
filter()
andincludes
const results = subjects.filter(function(s){
return s.includes(filters)
)};
- I tried converting the filter object to an array with the selected values eg;
let filters = ["red","green","full-time"]
and usedfilter()
andincludes
, but no luck
2
Answers
If you habe an object with same named properties, you could take a dynamic approach, by converting all items to arrays and check against.