I am attempting to filter an array of objects using multiple different filters. This currently works for an exact match but doesn't work for filtering using a substring. Is there a way to simply modify this filter function to to return all values that have a partial match?
nestedFilter(data, filters) {
let filterKeys = Object.keys(filters);
return data.filter(function (eachObj) {
return filterKeys.every(function (eachKey) {
if (!filters[eachKey].length) {
return true;
}
return filters[eachKey].includes(eachObj[eachKey]);
});
});
}
So using the below data and filters:
data = [
{
"NAME": "Johnathon",
"AGE": "19 ",
"GENDER": "M",
"SPORT": "Hockey",
"SCHOLARSHIP": "N"
},
{
"NAME": "Jessica",
"AGE": "20",
"GENDER": "F",
"SPORT": "Football",
"SCHOLARSHIP": "Y"
},
{
"NAME": "Matty",
"AGE": "20",
"GENDER": "NB",
"SPORT": "Tennis",
"SCHOLARSHIP": "Y"
},
{
"NAME": "Amy",
"AGE": "20",
"GENDER": "F",
"SPORT": "Football",
"SCHOLARSHIP": "N"
}
]
filters = [
{
"NAME": [],
"AGE": [],
"GENDER": [],
"SPORT": ["Foot", "Hockey"],
"SCHOLARSHIP": []
}
]
It should return Johnathon, Jessica and Amy objects.
(Filters in different fields act as AND and filters in the same field act as OR).
.includes()to.indexOf() != -1.some()instead of.every()