美文网首页
JS 数组去重

JS 数组去重

作者: FConfidence | 来源:发表于2017-09-11 16:55 被阅读10次
    var a = [1, 2, 3, '2', 3, 4, 5, 6, 6, 7, 8, 9, '0', 'a', 'a', 'b'];
    
    // set直接去重
    //var set = new Set(a)
    //console.log(set)
    
    Array.prototype.unique = function() {
      var newarr = [];
      var flag = true;
      for (var i = 0; i < this.length; i++) {
        for (var j = 0; j < newarr.length; j++) {
          if (newarr[j] === this[i]) {
            flag = false;
            break;
          } else {
            flag = true;
          }
        }
        if (flag) {
          newarr.push(this[i])
        }
      }
      return newarr;
    }
    
    Array.prototype.unique2 = function() {
      var newarr = [];
      var flag = true;
      var i = this.length;
      var j = 0;
      while ( --i > 0) {
        j = newarr.length;
        while (--j >= 0) {
          flag = newarr[j] !== this[i];
          if (!flag) {break}
        }
      flag && newarr.push(this[i])
      }
      return newarr.reverse();  //reverse 修改原始数组
    }
    
    // 对象去重法  数字和字符串数字无法去重
    Array.prototype.unique3 = function() {
      var obj = {}, newarr = [];
      for (var i = 0, length = this.length; i < length; i++ ) {
        //console.log(typeof this[i])
        obj[this[i]] = ""
      }
      console.log(obj)
    }
    
    Array.prototype.unique4= function() {
      var obj = {}, newarr = [];
      for (var i = this.length - 1; i >= 0; i -- ) {
        if (obj[this[i]] == undefined) {  //如果取的值在里面是undefined 即代表里面没有该数据
          obj[this[i]] = "";
          newarr.push(this[i]);
        }
      }
      return newarr;
    }
    
    // 保证数据类型的保留
    Array.prototype.unique5= function() {
      var obj = {}, newarr = [];
      for (var i = this.length - 1; i >= 0; i -- ) {
        if (obj[this[i]] == undefined || obj[this[i]] !== this[i]) { // 将字符串和非字符串区分
          obj[this[i]] = this[i];
          newarr.push(this[i]);
        }
      }
      return newarr.reverse();
    }
    
    Array.prototype.unique7 = function() {
      var obj = {}, newarr = [], i = this.length;
      while ( -- i >= 0) {
         (obj[this[i]] == undefined || obj[this[i]] !== this[i]) && (obj[this[i]] = this[i], newarr.push(this[i]))
      }
      return newarr.reverse();
    }
    
    //正则表达式法   不考虑字符串和数字类型的判断
    Array.prototype.unique8 = function() {
      return this.join(",").match(/([^,]+)(?!.*\1)/ig);
    }
    
    console.log(a.unique8())
    

    相关文章

      网友评论

          本文标题:JS 数组去重

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