JavaScript filtering by comparing two arrays

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

I want to loop through divsand hide those that do not have a category identifier in them data-catid.

I still have this:

$('.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 in 'itemCategories';

});
+4
source share
2 answers

Use as well as javascript (or a method can). filter() Array#every Array#some

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 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>
Run codeHide result

FYI: For an older browser, install the polyfill everymethod variant .

+8
source

You can use jquery .filter()instead .each()to filter the selected item and use String.prototype.indexOf()to check the value in the array.

var filters = [2, 4];
$('.myDiv').filter(function(){               
    var num = $(this).data('catid').split(',').map(Number);  
    return num.indexOf(filters[0]) == -1 || num.indexOf(filters[1]) == -1
}).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>
Run codeHide result
0

Source: https://habr.com/ru/post/1657351/


All Articles