• 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));
    学习在于积累:滴水可以石穿! 学而不思则罔,思而不学则殆!
  • 相关阅读:
    160720、SSM-Shiro使用详解
    Python学习(4)运算符
    Python学习(3)变量类型
    Python学习(2)基本语法
    Python学习(1)安装Python
    MonkeyRunner学习(3)脚本编辑
    MonkeyRunner学习(2)常用命令
    MonkeyRunner学习(1)测试连接
    Monkey学习(4)简单测试实例
    Monkey学习(3)如何在Android模拟器中安装apk
  • 原文地址:https://www.cnblogs.com/wyuan-yuan/p/9430105.html
Copyright © 2020-2023  润新知