I want to write a method which filters data for multiple criteria. These criteria should by passed as functions to the filter-function, for example:
var products = [/* some data */];
function filterMyProducts(criteria) {
return products.filter(/* I'm asking for this code */);
}
function cheap(product) {
return product.price < 100;
}
function red(product) {
return product.color == "red";
}
// find products that are cheap and red
var result = filterMyProducts([cheap, red]);
How can I combine the criteria passed in the array to the filter-function? I want them to be combined with a boolean AND.
function validateProduct(listOfFunctions) {
return function(currentProduct) {
return listOfFunctions.every(function(currentFunction) {
return currentFunction(currentProduct);
});
}
}
function filterMyProducts(criteria) {
return products.filter(validateProduct(criteria));
}
Working Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With