美文网首页
对象数组求差集,交集,并集

对象数组求差集,交集,并集

作者: 肥羊猪 | 来源:发表于2021-11-09 18:36 被阅读0次

    数组

    ES7新增了一个Array.prototype.includes的数组方法,用于返回一个数组是否包含指定元素,结合filter方法。

    a = [1, 2, 3],b = [2, 4, 5]
    // 并集
    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,4,5]
    

    ES6中新增的一个Array.from方法,用于将类数组对象和可遍历对象转化为数组。只要类数组有length长度,基本都可以转化为数组。结合Set结构实现数学集求解。

    let aSet = new Set(a)
    let bSet = new Set(b)
    // 并集
    let union = Array.from(new Set(a.concat(b))) // [1,2,3,4,5]
    // 交集
    let intersection = Array.from(new Set(a.filter(v => bSet.has(v)))) // [2]
    // 差集
    let difference = Array.from(new Set(a.concat(b).filter(v => !aSet.has(v) || !bSet.has(v)))) // [1,3,4,5]
    

    对象数组

    求交集

    var arr1 = [{name:'name1',id:1},{name:'name2',id:2},{name:'name3',id:3}];
    var arr1Id = [1,2,3]
    var arr2 = [{name:'name1',id:1},{name:'name2',id:2},{name:'name3',id:3},{name:'name4',id:4},{name:'name5',id:5}];
    var result = arr2.filter(function(v){
          return arr1Id.indexOf(v.id)!==-1 // 利用filter方法来遍历是否有相同的元素
    })
    
    求并集
          let arr1 = [{name:'name1',id:1},{name:'name2',id:2},{name:'name3',id:3}];
          let arr2 = [{name:'name1',id:1},{name:'name4',id:4},{name:'name5',id:5}];
          let arr3 = arr1.concat(arr2);
          let result = [];
          var obj = [];
          result = arr3.reduce(function(prev, cur, index, arr) {
            console.log(prev, cur);
            obj[cur.id] ? '' : obj[cur.id] = true && prev.push(cur);
            return prev;
          }, []);
    
    求差集   
       let arr1 = [{name:'name1',id:1},{name:'name2',id:2},{name:'name3',id:3}];
       let arr1Id = [1,2,3];
       let arr2 = [{name:'name1',id:1},{name:'name4',id:4},{name:'name5',id:5}];
       let arr2Id = [1,4,5];
       let arr3 = arr1.concat(arr2);
       let result = arr3.filter(function(v){
           return arr1Id.indexOf(v.id)===-1 || (arr2Id.indexOf(v.id)===-1)
       })
    

    相关文章

      网友评论

          本文标题:对象数组求差集,交集,并集

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