My goal is to create a function that can filter an array based on one or multiple conditions.
Let's examine this example data and filter criteria:
var data = [
{company: "Acme", fiscal_period: '01-2019', value: 10},
{company: "Acme", fiscal_period: '02-2019', value: 15},
{company: "Wonka", fiscal_period: '01-2019', value: 8},
{company: "Wonka", fiscal_period: '02-2019', value: 11}
]
var filter = [{field: "company", value: "Acme"}]
console.log(myFilterFunction(data,filter));
// Expected result
// [
// {company: "Acme", fiscal_period: '01-2019', value: 10},
// {company: "Acme", fiscal_period: '02-2019', value: 15}
// ]
// Now let's use two filters:
var filter = [{field: "company", value: "Acme"},{field: "fiscal_period", value: "01-2019"}]
console.log(myFilterFunction(data,filter);
// Expected result
// [
// {company: "Acme", fiscal_period: '01-2019', value: 10},
// ]
The question now is how to implement the myFilterFunction?
I understand how it works with a single static filter:
myFilterFunction = function(data,filter){
return data.filter(function(el){
return el[filter.field] === filter.value;
});
}
console.log(myFilterFunction(data,{field: "company", value: "Acme"});
But I am unsure how to make it dynamic when dealing with multiple filters.