• js 数组的交集、补集、并集


    // 交集
    const intersection = function (arr1,arr2) {
        let mergeArr = arr1 && arr2 && arr1.concat(arr2);
        arr1 = arr2Id(arr1);
        arr2 = arr2Id(arr2);
        let idArr = arr1 && arr1.filter(item=>arr2.includes(item));
        return id2Arr(idArr,mergeArr);
    }
    // 并集
    const union = function (arr1,arr2){
        let mergeArr = arr1 && arr2 && arr1.concat(arr2);
        let _arr1 = arr2Id(arr1);
        let _arr2 = arr2Id(arr2);
        let idArr = [...new Set(_arr1.concat(_arr2))];
        return id2Arr(idArr,mergeArr);
    }
    // 补集
    const complement = function(arr1,arr2){
        let mergeArr = arr1 && arr2 && arr1.concat(arr2);
        arr1 = arr2Id(arr1);
        arr2 = arr2Id(arr2);
        let idArr = arr1.filter(item=>!arr2.includes(item));
        return id2Arr(idArr,mergeArr);
    }
    
    // 提取对象数组中的对象id
    const arr2Id = (arr) => {
        return arr && arr.map(item=>item.id ? item.id : item);
    }
    // 通过id数组来还原对象数组
    const id2Arr = (idArr, arr) => {
        return idArr && idArr.map(id=>{
            let curr = id;
            arr && arr.forEach(item => item.id===id && (curr=item));
            return curr;
        })
    }
    
    
    
    
    
    /**
     * ============测试================
     */
    /**
     * 情形1:
    // 基本数据类型数组
     */
    
    const arr1=[1,2,3,5,6];
    const arr2=[1,2,6,7,8];
    /**
     * 情形2:
     * 对象类型数组
     */
    const objArr1=[
        {id:'001',name:'zhangsan'},
        {id:'002',name:'tom'},
        {id:'003',name:'jack'},
        {id:'004',name:'fei'},
        {id:'005',name:'ming'}
    ];
    const objArr2=[
        {id:'003',name:'jack'},
        {id:'005',name:'ming'},
        {id:'007',name:'hello'},
        {id:'008',name:'milk'},
    ];
    /**
     * 情形3:
     * 基本类型和对象杂糅
     */
    const multiArr1=[
        {id:'001',name:'zhangsan'},
        {id:'002',name:'tom'},
        {id:'003',name:'jack'},
        true,
        {id:'005',name:'ming'}
    ];
    const multiArr2=[
        {id:'003',name:'jack'},
        {id:'005',name:'ming'},
        true,
        {id:'008',name:'milk'},
    ];
    console.log('交集:',intersection(multiArr1,multiArr2));
    console.log('并集:',union(objArr1,objArr2));
    console.log('补集:',complement(arr1,arr2));
  • 相关阅读:
    刷脸背后:人脸检测人脸识别人脸检索_张重生资料整理
    webpack工具
    js精度缺失和最大安全整数
    在线文档预览(干货篇)
    讨论js比较两个数组(对象)是否相等的范围
    js不同数据类型中==与===的对比
    js中this的指向
    前后端数据类型
    js网页节点操作
    圆角渐变边框实现
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10312092.html
Copyright © 2020-2023  润新知