数组去重集合

使用对象键值对方式(推荐)
var ary = [12, 2, 1, 2, 232, 12, 3321]
            // 在原型中去添加去重的方法
        Array.prototype.Unique = function Unique() {
            // 使用对象的key唯一性,来去重
            var obj = {}
            for (var i = 0; i < this.length; i++) {
                var cur = this[i]
                if (obj[cur] == cur) {
                    // 就把数组当前项等于数组最后一项
                    this[i] = this[this.length - 1];
                    // 把数组最后一项删除
                    this.length--;
                    // for循环也跟着删除最后一项
                    i--;
                    continue
                }
                obj[cur] = cur
            }
            // 循环结束之后,就销毁临时的obj对象
            obj = null
            return this
        }

        // 调用原型中数组去重方法
        ary.Unique()
        console.log(ary)


 // 去重的前提是改变原有数组
  // 对象键值对方式去重
  Array.prototype.Unique = function () {
    var obj = {};
    for (var i = 0; i < this.length; i++) {
      var item = this[i]
      // 如果item在obj中有值,那就长度减去1,循环也减去1,退出本次循环
      if (typeof obj[item] !== 'undefined') {
        this[i] = this[this.length - 1];
        this.length--;
        i--;
        continue
      }
      obj[item] = true;

    }
    obj = null;
    return this
  }
  var arr = [12, 12, 23, 45, 56, 787, 23, 56]
  arr.Unique()
  console.log(arr)

2,双循环去重(不推荐)
  Array.prototype.Unique = function () {
    for (var i = 0; i < this.length; i++) {
      var item = this[i];
      for (var j = i + 1; j < this.length; j++) {
        // 如果当前项与后一项重复了
        if (item == this[j]) {
          this[i] = this[this.length - 1]
          this.length--;
          i--;
          break
        }
      }
    }
    return this
  }
  var arr = [12, 12, 23, 34, 45, 56, 56]
  arr.Unique()
  console.log(arr)
3,indexOf 去重(不兼容ie6-8)
// 3,indexOf 去重
  Array.prototype.Unique = function () {
    for (var i = 0; i < this.length; i++) {
      var item = this[i],
        //当前项与之后的所有进行比较,如果后面有,就删除当前项,对应的数组长度-1,循环-1 
        ary = this.slice(i + 1);
      if (ary.indexOf(item) > -1) {
        this[i] = this[this.length - 1];
        this.length--;
        i--;
      }
    }
    return this
  }
  var arr = [12, 12, 23, 323, 23]
  arr.Unique()
  console.log(arr)
4,排序后去重
 // 4,排序后相邻去除法
  Array.prototype.Unique = function () {
    var _this = this.sort(function (a, b) {
      return a - b
    });
    var ary = [];
    for (var i = 0; i < _this.length; i++) {
      var item = _this[i],
        next = _this[i + 1];
      if (item !== next) {
        ary.push(item)
      }

    }
    return ary
  }
  var ary = [12, 23, 12, 23, 23, 12]
  ary.Unique()
  console.log( ary.Unique())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值