zoukankan      html  css  js  c++  java
  • javascript 练习(2)——js数组去重

    今天遇到一个数组去重的问题,如题

    编写一个函数 unique(arr),返回一个去除数组内重复的元素的数组。例如:
    
    unique([0, 1, 2, 2, 3, 3, 4]) // => [0, 1, 2, 3, 4]
    unique([0, 1, '1', '1', 2]) // => [0, 1, '1', 2]

    比较容易想到的一种方法是利用indexOf方法:

     1 /*
     2 * 思路:新建一新数组,遍历传入数组,值不在新数组就push进该新数组中
     3 * IE8以下不支持数组的indexOf方法
     4 * */
     5 function unique(array){
     6     var temp = []; //一个新的临时数组
     7     for(var i = 0; i < array.length; i++){
     8         if(temp.indexOf(array[i]) == -1){
     9             temp.push(array[i]);
    10         }
    11     }
    12     return temp;
    13 }
    14 
    15 var aa = [1,2,2,4,9,6,7,5,2,3,5,6,5];
    16 console.log(unique(aa));

    然后还可以排序后比较相邻项去重:

     1 /*
     2 * 思路:给传入数组排序,排序后相同值相邻,
     3 * 然后遍历时,新数组只加入不与前一值重复的值。
     4 * 但是会打乱原来数组的顺序
     5 * */
     6 function unique(array){
     7     array.sort();
     8     var temp=[array[0]];
     9     for(var i = 1; i < array.length; i++){
    10         if( array[i] !== temp[temp.length-1]){
    11             temp.push(array[i]);
    12         }
    13     }
    14     return temp;
    15 }
    16 
    17 var aa = [1,2,"2",4,9,"a","a",2,3,5,6,5];
    18 console.log(unique(aa));

    做题时刚掌握了一种方法:

    [搬运] 新特性的写法

    1 const unique = (arr) => /*TODO*/Array.from(new Set(arr))

    只需要一行代码就够了,新特性简直不要太好用

  • 相关阅读:
    【亲测有效】安装npm慢的解决方案
    设置redis开机自动启动
    win10开启redis失败解决方案
    ajax跨域问题
    python进程不能并行的原因,进程阻塞
    python多进程并行代码
    python多进程间通信
    orangepi自启动打开一个终端并且运行脚本
    lxterminal命令打开新窗口并执行python脚本
    orangepi获取cpu温度
  • 原文地址:https://www.cnblogs.com/tttty/p/10537574.html
Copyright © 2011-2022 走看看