美文网首页
数组去重,两种比较好的方法。

数组去重,两种比较好的方法。

作者: sdcV | 来源:发表于2017-07-26 19:43 被阅读7次
    第一种
    1. 先将原数组进行排序

    2. 检查原数组中的第i个元素 与 结果数组中的最后一个元素是否相同,因为已经排序,所以重复元素会在相邻位置

    3. 如果不相同,则将该元素存入结果数组中

      Array.prototype.unique = 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, 's', 's', 'c', 'c', 's', 'd', 1, 9]
      alert(arr.unique());
      
    第二种
    1. 创建一个新的数组存放结果

    2. 创建一个空对象

    3. for循环时,每次取出一个元素与对象进行对比,如果这个元素不存在,则把它存放到结果数组中,同时把这个元素的内容作为对象的一个属性,并赋值为1,存入到第2步建立的对象中。

      Array.prototype.unique3 = function(){
          var res = [];
          var json = {};
          for(var i = 0; i < this.length; i++){
              if(!json[this[i]]){
                  res.push(this[i]);
                  json[this[i]] = 1;
              }
          }
          return res;
      }
      
    第三种
    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;
    }

    相关文章

      网友评论

          本文标题:数组去重,两种比较好的方法。

          本文链接:https://www.haomeiwen.com/subject/ctiokxtx.html