通过比较两个数组进行JavaScript过滤 [英] JavaScript filtering by comparing two arrays

查看:70
本文介绍了通过比较两个数组进行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.

这篇关于通过比较两个数组进行JavaScript过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆