使用jQuery的filter()函数提取具有不同条件的数组

时间:2011-09-07 16:49:29

标签: javascript jquery checkbox

我有一个存储在javascript中的基本数据集,我希望根据用户选中的复选框进行过滤。我知道我可以使用jQuery的filter()函数来过滤多个条件的结果集,但是我遇到的问题是标准会根据用户输入而改变。

var myArray = [["Adelaide", 2, "yes", "female"],
           ["Ada", 2, "yes", "female"],
           ["Amanda", 1, "yes", "female"],
           ["Wolf", 3, "no", "male"],
           ["Rhonda", 1, "no", "female"]];

HTML:

<input id="rate-3" name="rating" type="checkbox" value="rate-3" />3 Stars<br />
<input id="rate-2" name="rating" type="checkbox" value="rate-2" />2 Stars<br />
<input id="rate-1" name="rating" type="checkbox" value="rate-1" />1 Star<br />
<a href="#" id="submitform">Submit Filters</a>

如何将多个条件传递给.filter(函数)? 例如,有人可能选择rate-1和rate-3复选框,这是我目前硬编码要查找的函数,但我希望它根据用户提交的输入灵活。

我想我可以写一些if / else语句,但有更优雅的方法吗?

JQuery的:

$("#submitform").click(function() {
    var userSelectedFilters = new Object();

    userSelectedFilters.rate3 = $("#rate-3").is(':checked');
    userSelectedFilters.rate2 = $("#rate-2").is(':checked');
    userSelectedFilters.rate1 = $("#rate-1").is(':checked');

    var filteredArray = myArray.filter(
    function(el) {
       // currently hardcoded
       return ((el[1] == 1) || (el[1] == 3));
     }
    );

});

3 个答案:

答案 0 :(得分:2)

构建一个数组并检查数组中是否包含该数字:DEMO

$("#submitform").click(function() {
    var userSelectedFilters = [];

    $("#rate-3").is(':checked') && userSelectedFilters.push(3);
    $("#rate-2").is(':checked') && userSelectedFilters.push(2);
    $("#rate-1").is(':checked') && userSelectedFilters.push(1);

    var filteredArray = myArray.filter(
    function(el) {
       // currently hardcoded
        return userSelectedFilters.indexOf(el[1]) !== -1;
     }
    );
});

indexOf不是普遍的,但有一个垫片:

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this === void 0 || this === null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n !== n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n !== 0 && n !== window.Infinity && n !== -window.Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

答案 1 :(得分:1)

你可以查看你的html,并为每个盒子使用name =“rating []”,它会为你节省很多头脑。

实际上,在你的提交功能中:

$('input:checked').each( function () {
   userSelectedFilters[this.id] = this.id;
});

但同样,可以避免完整的stackofcode,只需对stackoverflow(或谷歌)进行一些研究。无论如何:这是你的代码:

var myArray = [["Adelaide", 2, "yes", "female"],
           ["Ada", 2, "yes", "female"],
           ["Amanda", 1, "yes", "female"],
           ["Wolf", 3, "no", "male"],
           ["Rhonda", 1, "no", "female"]];

$("#submitform").click(function() {

    var choices = [];

    $('input:checked').each( function () {
       choices.push(this.id.charAt(this.id.length-1)); 

    });


    var filteredArray = myArray.filter(
    function(el) {

       for (i in choices) {
            if ( choices[i] == el[1] ) {
                return true;
            }
       }
       return false
     }
    );

    console.log (filteredArray );

});

答案 2 :(得分:1)

你可以这样做:

var myArray = [["Adelaide", 2, "yes", "female"],
           ["Ada", 2, "yes", "female"],
           ["Amanda", 1, "yes", "female"],
           ["Wolf", 3, "no", "male"],
           ["Rhonda", 1, "no", "female"]];

$("#submitform").click(function() {

    var userSelectedFilters = [];
    $("input:checkbox:checked").each(function(){
         userSelectedFilters.push(this.value)
    });



    var filteredArray = myArray.filter(
    function(el) {
       // currently hardcoded
        for (i =0, lungh = userSelectedFilters.length ; i< lungh; i++){
            console.log(userSelectedFilters[i]);
            if (el[1] == userSelectedFilters[i]){
               return true;
            }

        }
        return false;
     }
    );


});

在这里摆弄:http://jsfiddle.net/pWJwt/