我们如何在jquery中将数组与数组中的数组进行比较

时间:2017-06-21 08:05:16

标签: javascript jquery

实施例

var array1=['1','2','3','4'];
var array2=['1,2,3,4,5','1,2,3,6','1,7,8,9'];

比较这两个数组。

我试试这段代码:

for (var i = 0; i < array1.length; i++) {
    for (var j= 0; j< array2.length; j++) {
      if()
      --------
    }
}

先谢谢

2 个答案:

答案 0 :(得分:2)

您可以使用array1的拆分项的任意值检查array2的每个值。

ES5

&#13;
&#13;
var array1 = ['1', '2', '3', '4'],
    array2 = ['1,2,3,4,5', '1,2,3,6', '1,7,8,9'],
    check = array2.some(function (c) {
        return array1.every(function (b) {
            return function (a, i) {
                return a === b[i];
            };
        }(c.split(',')));
    });
    
console.log(check);
&#13;
&#13;
&#13;

ES6

&#13;
&#13;
var array1 = ['1', '2', '3', '4'],
    array2 = ['1,2,3,4,5', '1,2,3,6', '1,7,8,9'],
    check = array2.some(c => array1.every((b => (a, i) => a === b[i])(c.split(','))));
    
console.log(check);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尝试使用join(',')includes()方法。

已更新

  1. 返回匹配的参数

  2. 使用Array#reduce帮助匹配每个array1参数

  3. &#13;
    &#13;
    var array1 = ['1','2', '4'];
    var array2 = ['1,2,3,4,5', '1,2,3,6', '1,7,8,9'];
    var res = array2.reduce(function(a, b) {
      array1.forEach(function(val) {
        if (b.includes(val) && !a.includes(b)) {
          a.push(b);
        }
      })
      return a;
    }, [])
    console.log(res);
    console.log(res.length > 0)
    &#13;
    &#13;
    &#13;