【问题标题】:How to have multiple filter on an JQuery Array如何在 JQuery 数组上有多个过滤器
【发布时间】:2011-08-16 21:31:15
【问题描述】:

我目前有一些代码可以使用滑块根据价格范围过滤数组。我需要能够为各种尺寸和颜色添加复选框,以便我还可以使用它们的值进行过滤。这是我到目前为止的代码,但不确定如何实现复选框,以便我有多种过滤数组的方法。

//this is the main generated array
    var product = [{"price":"200","color":"red","size":"small"},
                   {"price":"250","color":"brown","size":"medium"},
                   {"price":"300","color":"red","size":"large"}];

// array to display filtered array
    var filteredProducts = [];  
    var key = 0;

//start of price range filter
    if(!minPrice && !maxPrice){
       filteredProducts = products;
    } else{
       $.each(products, function(i, object) {   
           var curentPrice = parseFloat(object.price); 
           var priceMinOk = true;
           var priceMaxOk = true;
       // filter results match the price range
           if(maxPrice || minPrice){
              if(maxPrice && maxPrice<curentPrice){
                 priceMaxOk = false;
              }
              if(minPrice && minPrice>curentPrice){
                 priceMinOk = false;
              }
           }  
       //  loop over list and get only related to new array
           if( priceMinOk && priceMaxOk ){  
              filteredProducts[key] = object;                  
              key++;
           }  
       });
    } 

提前感谢您的帮助”

小提琴http://jsfiddle.net/ltbmedia/86pEn/

【问题讨论】:

    标签: jquery arrays filter


    【解决方案1】:

    使用$.grep 代替$.each,并像这样构造代码:

    var products = [ /* ... */ ],
        predicates = [
            function predicate1(obj) { /* ... */ },
            function predicate2(obj) { /* ... */ },
            // ... ,
            function predicateN(obj) { /* ... */ }
        ],
        filteredProducts;
    
    filteredProducts = $.grep(products, function (element, index)
    {
        for (var i=0; i<predicates.length; i++)
        {
            if (!predicates[i](element)) return false;
        }
    
        return true;
    });
    

    示例:http://jsfiddle.net/mattball/Rsbcu/


    更复杂的例子:http://jsfiddle.net/mattball/vZzjM/

    您可能会注意到仍然返回一个空数组,但这实际上是有道理的。鉴于您指定的条件 (minPrice = 201, maxPrice = 301, color = red or green, size = small)没有匹配的数组元素。

    将价格标准放宽一点微小,您会发现一切正常:http://jsfiddle.net/mattball/MQ8Mc/

    【讨论】:

    • 谢谢马特,我假设每个 'function predicate1(obj) { /* ... */ } 都是针对每个过滤器元素(即大小)的,对吗?
    • 没错。每个谓词将测试每个元素上的单独条件。在您问题的示例代码中,您将使用两个谓词,一个用于测试最低价格条件,一个用于测试最高价格条件。顺便说一句,谓词是一个返回布尔值的函数。
    • 再次感谢,但我不确定我完全明白你的意思。一个特定元素值的预测函数如何测试,对不起,我整天都在用这个头撞墙!
    • 嗨,马特,谢谢你,我认为这让事情变得更清楚了!您是否可以查看我的编辑并查看我哪里出错了,现在得到一个空数组,我可以使用这种方法使用多个复选框吗?谢谢...
    • 对于初学者,您正在尝试parseFloat 颜色和尺寸,但这是行不通的......
    猜你喜欢
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 2020-11-27
    相关资源
    最近更新 更多