数组的差集、交集、去重

普通数组

   
    let a = [1, 2, 3, 4, 5, 6]
    let b = [4, 5, 6, 7, 8, 9]
    // 并集 数组去重 
    let RemoveSame = new Set([...a, ...b])
    console.log(new Set([...a, ...b])) //[1, 2, 3, 4, 5, 6, 7, 8, 9]

    //数组交集,或得两个数组重复的元素
    let SamePart = a.filter(item => b.includes(item))
    console.log(SamePart) //[4, 5, 6]

    //a在b中不存在的差集
    let Difference = a.filter(item => !b.includes(item))
    console.log(Difference) //[1, 2, 3, 7, 8, 9]
    
    //差集=并集-交集  去除两个数组相同的元素 
    let SamePartAll = Array.from(RemoveSame) //RemoveSame转换为数组
    Difference = SamePartAll.filter(item => !SamePart.includes(item))
    console.log(Difference) //[1, 2, 3, 7, 8, 9]
    

es6数组去重

function newArr(arr){
    return Array.from(new Set(arr))
}
 
var arr = [1,1,2,9,6,9,6,3,1,4,5];
 
console.log(newArr(arr))

对象数组

  
    let arr1 = [
      { key: 1, id: 8, val: "a" },
      { key: 2, id: 9, val: "b" },
      { key: 4, id: 14, val: "c" },
      { key: 3, id: 15, val: "d" },
    ];
    let arr2 = [
      { key: 1, id: 8, val: "a" },
      { key: 2, id: 9, val: "b" },
      { key: 5, id: 8, val: "e" },
      { key: 6, id: 9, val: "f" },
      { key: 5, id: 19, val: "g" },
      { key: 6, id: 22, val: "h" },
      { key: 5, id: 19, val: "g" },
      { key: 6, id: 22, val: "h" }
    ];
    let arr = [...arr1, ...arr2]
    let arr3;


    //根据关键字取差集
    arr3 = [...arr2].filter(x => [...arr1].every(y => y.id !== x.id));
    console.log("根据关键字取差集=", arr3)
    //全部匹配取差集 
    arr3 = arr2.filter(v => {
      var str = JSON.stringify(v);
      return arr1.every(v => JSON.stringify(v) != str);
    });
    console.log("全部匹配取差集=", arr3);
    //根据关键字去重
    // 利用reduce 
    const hash = {};
    const newArray = arr.reduce((item:any, next:any) => {
      hash[next.id] ? '' : hash[next.id] = true && item.push(next);
      return item;
    }, [])
    console.info('根据关键字去重后的数组=', newArray);
    //根据关键字去重 
    const keyArr: any = [];
    arr.forEach((element: any, index: any) => {
      keyArr.push(element.key);  // 通过key来判断
    });
    const newArr: any = [];
    const newKey = new Set(keyArr);  // key去重
    newKey.forEach(item => {
      const index = keyArr.findIndex(item2 => item2 === item);
      newArr.push(arr[index]);
    })
    console.info('根据关键字去重后的数组2:', newArr);
     //去重
    let res = new Map();
    this.dialog.chooseList = await this.dialog.chooseList.filter(
      (item: any) => !res.has(item.itemId) && res.set(item.itemId, 1)
    );
    // 关键字交集
    arr3 = [...arr2].filter(x => [...arr1].some(y => y.id === x.id));
    console.log("关键字交集=", arr3);


在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值