zoukankan      html  css  js  c++  java
  • js数组去重的常用方法总结

    最近几天朋友面试了几家,笔试题都做了关于数组去重的问题,自己在网上收集整理了一些去重的方法来学习下,感觉换不错哈!!!
    第一种方法:
      function oSort(arr){
        var n = []; //一个新的临时数组
        for(var i = 0; i < arr.length; i++) //遍历当前数组
          {
          //如果当前数组的第i已经保存进了临时数组,那么跳过,
          //否则把当前项push到临时数组里面
        if (n.indexOf(arr[i]) == -1) n.push(arr[i]);
          }
        console.log(n)
        return n;
        }
        var arr = [1,2,3,4,4,4,5,5,6,7,8,9]
        oSort(arr)

    第二种方法:

        Array.prototype.unique2 = function(){
        this.sort(); //先排序
        var res = [this[0]];
        for(var i = 1; i < this.length; i++){
        if(this[i] !== res[res.length - 1]){
        res.push(this[i]);
        }
        }
          return res;
        }
        var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, 0]
        alert(arr.unique2());

    第三种方法:
        Array.prototype.unique3 = function()
        {
        var n = [this[0]]; //结果数组
        for(var i = 1; i < this.length; i++) //从第二项开始遍历
        {
        //如果当前数组的第i项在 当前数组中第一次出现的位置不是i,
        //那么表示第i项是重复的,忽略掉。否则存入结果数组
        if (this.indexOf(this[i]) == i) n.push(this[i]);
        }
        return n;
        }
        var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, 0]
        alert(arr.unique3());
        第四种方法:

        Array.prototype.unique4 = function()
        {
        this.sort();
        var res=[this[0]];
        for(var i = 1; i < this.length; i++)
        {

        if( this[i] !== res[res.length-1]){
        res.push(this[i]);
        }
        }
        return res;
        }

        var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, 0]
        alert(arr.unique4());

  • 相关阅读:
    codeforces 616B Dinner with Emma
    codeforces 616A Comparing Two Long Integers
    codeforces 615C Running Track
    codeforces 612C Replace To Make Regular Bracket Sequence
    codeforces 612B HDD is Outdated Technology
    重写父类中的成员属性
    子类继承父类
    访问修饰符
    方法的参数
    实例化类
  • 原文地址:https://www.cnblogs.com/fly-xfa/p/5680756.html
Copyright © 2011-2022 走看看