How to filter an array/object by checking multiple values

后端 未结 2 376
执笔经年
执笔经年 2020-12-03 10:07

I\'m playing around with arrays trying to understand them more since I tend to work with them alot lately. I got this case where I want to search an array and compare it\'s

相关标签:
2条回答
  • 2020-12-03 10:24

    You can use .filter() with boolean operators ie &&:

         var find = my_array.filter(function(result) {
           return result.param1 === "srting1" && result.param2 === 'string2';
         });
         
         return find[0];
    
    0 讨论(0)
  • 2020-12-03 10:49

    You can use .filter() method of the Array object:

    var filtered = workItems.filter(function(element) {
       // Create an array using `.split()` method
       var cats = element.category.split(' ');
    
       // Filter the returned array based on specified filters
       // If the length of the returned filtered array is equal to
       // length of the filters array the element should be returned  
       return cats.filter(function(cat) {
           return filtersArray.indexOf(cat) > -1;
       }).length === filtersArray.length;
    });
    

    http://jsfiddle.net/6RBnB/

    Some old browsers like IE8 doesn't support .filter() method of the Array object, if you are using jQuery you can use .filter() method of jQuery object.

    jQuery version:

    var filtered = $(workItems).filter(function(i, element) {
       var cats = element.category.split(' ');
    
        return $(cats).filter(function(_, cat) {
           return $.inArray(cat, filtersArray) > -1;
        }).length === filtersArray.length;
    });
    
    0 讨论(0)
提交回复
热议问题