通过比较两个数组进行JavaScript过滤

问题描述:

DOM:

<div class='myDiv' data-catid='1,2,3'></div>
<div class='myDiv' data-catid='4,5'></div>
<div class='myDiv' data-catid='1,5,7'></div>
<div class='myDiv' data-catid='8,9'></div>
<div class='myDiv' data-catid='2,3,4'></div>

JS:

var filters = [2, 4];

我想循环遍历 divs ,并隐藏那些在 data-catid 中没有类别ID的那些。

I want to loop through the divs, and hide the ones that doesn't have both of the category ID's in their data-catid.

我有到目前为止:

$('.myDiv').each(function(i, el){               

  var itemCategories = $(el).data('catId').split(',');

  // Do check and then hide with $(el).css('visibility', 'hidden') 
  // if doesn't contain both filter id's in 'itemCategories';

});


使用 filter() 方法以及javascript Array#every 方法(或 可以使用数组#some 方法。)

Use filter() method along with javascript Array#every method(or Array#some method can be used).

var filters = [2, 4];

// get all elements with class `myDiv`
$('.myDiv')
  // filter out elements
  .filter(function() {
    // generate array from catid attribute
    var arr = $(this)
      // get data attribute value
      .data('catid')
      // split based on `,`
      .split(',')
      // parse the string array, it's optional 
      // if you are not parsing then convert Number to 
      // String while using with indexOf
      .map(Number);
    // check all catid presents 
    return !filters.every(function(v) {
      // check index of elements
      return arr.indexOf(v) > -1;
    });
    // or with `some` method 
    // return filters.some(function(v) { return arr.indexOf(v) === -1; });  
    // hide the elements
  }).hide();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='myDiv' data-catid='1,2,3'>1</div>
<div class='myDiv' data-catid='4,5'>2</div>
<div class='myDiv' data-catid='1,5,7'>3</div>
<div class='myDiv' data-catid='8,9'>4</div>
<div class='myDiv' data-catid='2,3,4'>5</div>

FYI:对于较旧的浏览器,请检查 每个方法的polyfill选项

FYI : For older browser check polyfill option of every method.