欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

javascript数组去重方法总结

程序员文章站 2023-09-08 23:26:35
第一种--对象键值去重 第二种--splice删除去重 第三种--利用数组indexOf方法 第四种--数组下标 第五种 第六种 第七种--es6 set 第八种--filter ......

 第一种--对象键值去重

    array.prototype.unique1 = function () {
      var r = {},
        temp = []
      for (var i = 0; i < this.length; i++) {
        if (!r[this[i]]) {
          r[this[i]] = 1
          temp.push(this[i])
        }
      }
      return temp
    }

第二种--splice删除去重

    array.prototype.unique2 = function () {
      for (var i = 0; i < this.length; i++) {
        for (var j = i + 1; j < this.length; j++) {
          if (this[i] === this[j]) {
            this.splice(j, 1)
            j--
          }
        }
      }
      return this
    }

第三种--利用数组indexof方法

    // 循环遍历当前数组,当前不在临时数组的,push
    array.prototype.unique3 = function () {
      var temp = []
      for (var i = 0; i < this.length; i++) {
        if (temp.indexof(this[i]) === -1) temp.push(this[i])
      }
      return temp
    }

第四种--数组下标

    // 当前数组的第i项在当前数组第一次出现的位置不是i,当前项即重复,反之
    array.prototype.unique4 = function () {
      var temp = [this[0]]
      for (var i = 1; i < this.length; i++) {
        if (this.indexof(this[i]) === i) temp.push(this[i])
      }
      return temp
    }

第五种

    // 先排序,找相邻的项
    // 这个会改变原来数组的顺序
    array.prototype.unique5 = function () {
      var temparr = this.sort(),
        temp = [temparr[0]]
      for (var i = 1; i < temparr.length; i++) {
        if (temparr[i] !== temp[temp.length - 1]) temp.push(temparr[i])
      }
      return temp
    }

第六种

    // 优化遍历数组
    // 获取没重复的最右一值放入新数组
    array.prototype.unique6 = function () {
      var temp = []
      for (var i = 0; i < this.length; i++) {
        for (j = i + 1; j < this.length; j++) {
          if (this[i] === this[j]) {
            i++;
            j = i;
          }
        }
        temp.push(this[i])
      }
      return temp
    }

第七种--es6 set

    array.prototype.unique7 = function () {
      var temp = new set(this)
      return [...temp]
    }

第八种--filter

    array.prototype.unique8 = function () {
      return this.filter(function (ele, index, self) {
        return self.indexof(ele) === index;
      })
    }