Skip to content Skip to sidebar Skip to footer

Javascript Filtering By Comparing Two Arrays

The DOM:
&l

Solution 1:

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 attributevar 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 elementsreturn arr.indexOf(v) > -1;
    });
    // or with `some` method // return filters.some(function(v) { return arr.indexOf(v) === -1; });  // hide the elements
  }).hide();
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass='myDiv'data-catid='1,2,3'>1</div><divclass='myDiv'data-catid='4,5'>2</div><divclass='myDiv'data-catid='1,5,7'>3</div><divclass='myDiv'data-catid='8,9'>4</div><divclass='myDiv'data-catid='2,3,4'>5</div>

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

Solution 2:

You can use jquery .filter() instead .each() to filtering selected element and use String.prototype.indexOf() to check value exist in 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();
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass='myDiv'data-catid='1,2,3'>1</div><divclass='myDiv'data-catid='4,5'>2</div><divclass='myDiv'data-catid='1,5,7'>3</div><divclass='myDiv'data-catid='8,9'>4</div><divclass='myDiv'data-catid='2,3,4'>5</div>

Post a Comment for "Javascript Filtering By Comparing Two Arrays"