美文网首页
多个数组取交集

多个数组取交集

作者: 羊绘霖 | 来源:发表于2020-09-15 17:03 被阅读0次
    var profession = ["cat", "dog","pig","duck"];
    var a = {
      "cat": [1, 2, 3, "12", 4, 22, 11],
      "pig": [2, 3, "12"],
      "dog": [2, 4, 3, "12", 11],
      "duck":[2,11]
    };
    var jiaoji = a.cat;
    var re = profession.reduce(function(pre, cur, index, array) {
      jiaoji = jiaoji.filter(function(n) {
        return a[cur].indexOf(n) != -1;
      }); 
      return jiaoji;
    
    },a.cat);
     console.log(jiaoji);
    
    // 并集
    let union = a.concat(b.filter(v => !a.includes(v))) // [1,2,3,4,5]
    // 交集
    let intersection = a.filter(v => b.includes(v)) // [2]
    // 差集
    let difference = a.concat(b).filter(v => a.includes(v) && !b.includes(v)) // [1,3]
    

    相关文章

      网友评论

          本文标题:多个数组取交集

          本文链接:https://www.haomeiwen.com/subject/jgmfyktx.html