Javascript:Concat布尔函数

时间:2014-03-05 13:28:24

标签: javascript filter boolean concat

我想编写一个过滤多个条件数据的方法。这些标准应作为函数传递给filter-function,例如:

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]);

如何将数组中传递的条件与filter-function相结合?我希望它们与布尔 AND 结合使用。

2 个答案:

答案 0 :(得分:6)

function validateProduct(listOfFunctions) {
    return function(currentProduct) {
        return listOfFunctions.every(function(currentFunction) {
            return currentFunction(currentProduct);
        });
    }
}

function filterMyProducts(criteria) {
    return products.filter(validateProduct(criteria));
}

Working Demo

答案 1 :(得分:1)

可以在这里使用reduce功能,如下所示:

function filterMyProducts(criteria) {
  return criteria.reduce(function(prev, curr) {
    return prev.filter(curr)
  }, products)
}