zoukankan      html  css  js  c++  java
  • js 二维数组去重(续)

    二维数组去重,说白了就是删除重复项。今天看到有兄弟评论说代码有问题,非常感谢这位兄弟。重新修改了一下代码,如若发现我的其他blog也有问题的话,也希望能指出来,我们一起学习一起提高。代码如下:

    /**
     * 方法一
     * @param {*} arr 
     */
    const removeRepeat1 = (arr) => {
      const obj={};
      return arr.filter(item=>{
        if(!obj[item.toString()]) {
          obj[item.toString()]=item.toString();
          return item;
        }
      });
    }
    /**
     * 方法二
     * @param {*} arr 
     */
    const removeRepeat2 = (arr) => {
      const obj={};
      arr.forEach(item=>!obj[item.toString()] && (obj[item.toString()]=item));
      return Object.values(obj);
    }
    
    
    
    // 测试结果
    const matrix=[
      [1,2,3,4],
      [3,4,5,6],
      [1,2,3,4]
    ]
    
    const ans1=removeRepeat1(matrix);//[ [ 1, 2, 3, 4 ], [ 3, 4, 5, 6 ] ]
    const ans2=removeRepeat2(matrix);//[ [ 1, 2, 3, 4 ], [ 3, 4, 5, 6 ] ]
    console.log(ans1);
    console.log(ans2);

    以上代码并不完善,很多容错都没做,但核心的思想能勾传达出来,即间接的将二维数组转化为一维字符串数组的形式来进行去重。具体容错考虑后面我会添加上去,现在先写下测试用例,即matrix可能有哪些值

    二维数组我们暂且称之为矩阵,下面都用这个别名。
    1. 边界情况,例如null、undefined、非数组、非矩阵
    2. 矩阵的每一项都是一个对象类型
    3. 正常情况即数字数组
  • 相关阅读:
    poj 2325 Persistent Numbers (贪心+高精度)
    迷宫 (BFS)
    poj1087 A Plug for UNIX & poj1459 Power Network (最大流)
    hdu 3549 Flow Problem (最大流)
    CodeForces Round #179 (295A)
    poj 1328 Radar Installation
    HTML 网页游戏 2048
    图论加边算法--链式向前星
    c语言 字符版 简易2048
    POJ 2115 C Looooops(扩展欧几里得)
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/9775711.html
Copyright © 2011-2022 走看看