• js 实现json数组集合去重,差集,并集,交集。


          let list = [
            {
              id: "1",
              content: "A"
            },
            {
              id: "2",
              content: "B"
            },
            {
              id: "3",
              content: "C"
            },
            {
              id: "4",
              content: "D"
            }
          ];
          let arr = [
            {
              id: "1",
              content: "C"
            },
            {
              id: "2",
              content: "D"
            }
          ];
    
          // let list = [1, 2, 3, 4, 5];
          // let arr = [3, 4];
    
          // 去重
          function listRemoveRepeat(x) {
            let result = [];
            for (let i = 0; i < x.length; i++) {
              let flag = true;
              let temp = x[i];
              for (let j = 0; j < result.length; j++) {
                // 普通数组 (temp === result[j])
                if (temp.id === result[j].id) {
                  flag = false;
                  break;
                }
              }
              if (flag) {
                result.push(temp);
              }
            }
            return result;
          }
          // 差集
          function listDifference(x, y) {
            let clone = x.slice(0);
            for (let i = 0; i < y.length; i++) {
              let temp = y[i];
              for (let j = 0; j < clone.length; j++) {
                // 普通数组 (temp === clone[j])
                if (temp.id === clone[j].id) {
                  clone.splice(j, 1);
                }
              }
            }
            return listRemoveRepeat(clone);
          }
          // 并集
          function listConcat(x, y) {
            return listRemoveRepeat(x.concat(y));
          }
          // 交集
          function listIntersection(x, y) {
            let result = [];
            for (let i = 0; i < y.length; i++) {
              let temp = y[i];
              for (let j = 0; j < x.length; j++) {
                // 普通数组 (temp === clone[j])
                if (temp.id === x[j].id) {
                  result.push(temp);
                  break;
                }
              }
            }
            return listRemoveRepeat(result);
          }
          console.log("去重", listRemoveRepeat(list));
          console.log("差集", listDifference(list, arr));
          console.log("并集", listConcat(list, arr));
          console.log("交集", listIntersection(list, arr));
    学习在于积累:滴水可以石穿! 学而不思则罔,思而不学则殆!
  • 相关阅读:
    小程序自定义组件(3)子向父传参
    postgresql插件安装
    二进制减法的实现
    mysql锁表问题
    mysql查看修改参数
    众数问题-找出超过一半的数
    只出现一次的数
    元素最大间距离
    第一个缺失数字
    局部最小值位置
  • 原文地址:https://www.cnblogs.com/wyuan-yuan/p/9430105.html
Copyright © 2020-2023  润新知