• js数组去重及数组对象去重


    var arr = [1,2,3,5,3,4,5,6,6,"test","test",true];

    var person = [
      {
        name:"孙悟空",
        weapon:"如意金箍棒",
        experience:"大闹天宫、西天取经",
        post:"斗战胜佛、齐天大圣"
      },
      {
        name:"孙悟空",
        weapon:"如意金箍棒",
        experience:"大闹天宫、西天取经",
        post:"斗战胜佛、齐天大圣"
      },
      {
        name:"孙悟空",
        weapon:"如意金箍棒",
        experience:"大闹天宫、西天取经",
        post:"斗战胜佛、齐天大圣"
      },
      {
        name:"孙悟空",
        weapon:"如意金箍棒",
        experience:"大闹天宫、西天取经",
        post:"斗战胜佛、齐天大圣"
      },
      {
        name:"孙悟空",
        weapon:"如意金箍棒",
        experience:"大闹天宫、西天取经",
        post:"斗战胜佛、齐天大圣"
      }
    ];
    //ES5原生去重办法
    function Es5duplicate(arr,type){
      var newArr = [];
      var tArr = [];
      if(arr.length == 0){
        return arr;
      }else{
        if(type){
          for(var i = 0; i < arr.length;i++){
            if(!tArr[arr[i][type]]){
              newArr.push(arr[i]);
              tArr[arr[i][type]] = true;
            }
          }
          return newArr;
        }else{
          for(var i = 0; i < arr.length;i++){
            if(!tArr[arr[i]]){
              newArr.push(arr[i]);
              tArr[arr[i]] = true;
            }
          }
          return newArr;
        }
      }
    }
    console.log('ES5去重',Es5duplicate(arr));
    console.log('ES5去重',Es5duplicate(person,"name"));
    //Es6 + ES5去重办法
    function Es6duplicate(arr,type){
      if(arr.length == 0){
        return arr;
      }else{
        if(type){
          var obj = {}
          var newArr = arr.reduce((cur,next) => {
            obj[next.name] ? "" : obj[next.name] = true && cur.push(next);
            return cur;
          },[])
          return newArr;
        }else{
          return Array.from(new Set(arr));
        }
      }
    }
    console.log('ES6去重',Es6duplicate(arr));
    console.log('ES6去重',Es6duplicate(person,"name"));
  • 相关阅读:
    解题报告 百进制数
    解题报告 Loongint 的夜晚
    解题报告 树形图计数
    解题报告 一元三次方程求解
    解题报告 Loongint 的旅行安排
    解题报告 数字查找
    用C++编写简单绘图语言的词法分析器——程序清单
    C++ 连接 mysql 的一个例子(Visual Studio 2005)
    fedora 8 下JDK 6.0 配置
    IBM DB2 V9 常用命令
  • 原文地址:https://www.cnblogs.com/snowhite/p/15352998.html
Copyright © 2020-2023  润新知