数组去重

1、遍历数组法

描述:新建一新数组,遍历传入数组,值不在新数组就加入该新数组中。

  

Array.prototype.unique = function () {
    var arr = [];
    for (var i = 0, len = this.length; i < len; i++) {
        if (arr.indexOf(this[i]) === -1) {
            arr.push(this[i]);
        }
    }
    return arr;
}

// 调用
var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, 0];
console.log(arr.unique());  // [1, "a", "b", "d", "e", 0]

2、对象键值对法

描述:新建对象以及数组,遍历传入数组时,判断值是否为对象的键,不是的话给对象新增该键并放入新数组。注意点: 判断是否为对象键时,会自动对传入的键执行“toString()”,不同的键可能会被误认为一样;例如: a[1]、a["1"] 。解决上述问题还是得调用“indexOf”。

Array.prototype.unique = function () {
    var obj = [],
        arr = [],
        val = '',
        type = '';

    for (var i = 0, len = this.length; i < len; i++) {
        val = this[i];
        type = typeof val;
        
        // 若不存在obj[val],则val一定会被push进arr
        if (!obj[val]) {
            // 将val的数据类型存放到obj[val],处理极端情况会用到
            obj[val] = [type];
            arr.push(val);
        } else if (obj[val].indexOf(type) < 0) {  
            // 若obj[val]已存在(键值会执行toString()转换,可能会得到相同的obj[val],但obj[val]里的type一定是唯一的)
            obj[val].push(type);
            arr.push(val);
        }
    }

    return arr;
}

var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, '1', '1', 0];
console.log(arr.unique());  // [1, "a", "b", "d", "e", "1", 0]

3、数组下标判断法

如果当前数组的第i项在当前数组中第一次出现的位置不是i,那么表示第i项是重复的,忽略掉。否则存入结果数组。

Array.prototype.unique = function () {
    var arr = [this[0]]; //结果数组

    //从第二项开始遍历
    for(var i = 1, len = this.length; i < len; i++) {
        //如果当前数组的第i项在当前数组中第一次出现的位置不是i,
        //那么表示第i项是重复的,忽略掉。否则存入结果数组
        if (this.indexOf(this[i]) === i) {
            arr.push(this[i]);
        }
    }

    return arr;
}

var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, '1', '1', 0];
console.log(arr.unique()); // [1, "a", "b", "d", "e", "1", 0]

4、排序后相邻去除法

描述:给传入数组排序,排序后相同值相邻,然后遍历时新数组只加入不与前一值重复的值。

Array.prototype.unique = function () {
    this.sort();

    var arr = [this[0]];

    for(var i = 1; i < this.length; i++){
        if( this[i] !== arr[arr.length-1]) arr.push(this[i]);
    }

    return arr;
}

var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, '1', '1', 0];
console.log(arr.unique());  // [0, 1, "1", 1, "a", "b", "d", "e"]

5、优化遍历数组法

获取没重复的最右一值放入新数组。(检测到有重复值时终止当前循环同时进入顶层循环的下一轮判断)

Array.prototype.unique = function () {
    var arr = [];

    for(var i = 0, len = this.length; i < len; i++) {
        for(var j = i + 1; j < len; j++) {
            if (this[i] === this[j]) j = ++i;
        }
        arr.push(this[i]);
    }

    return arr;
}

var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, '1', '1', 0];
console.log(arr.unique());  // ["a", "b", "d", "e", 1, "1", 0]

6、遍历数组法

最简单的去重方法,实现思路:新建一新数组,遍历传入数组,值不在新数组就加入该新数组中;注意点:判断值是否在数组的方法“indexOf”是ECMAScript5 方法,IE8以下不支持,需多写一些兼容低版本浏览器代码,源码如下:

//判断浏览器是否支持indexOf ,indexOf 为ecmaScript5新方法 IE8以下(包括IE8, IE8只支持部分ecma5)不支持

if (!Array.prototype.indexOf) {
    // 新增indexOf方法 
    Array.prototype.indexOf = function(item) {
        var result = -1
          , a_item = null;
        if (this.length == 0) {
            return result;
        }
        for (var i = 0, len = this.length; i < len; i++) {
            a_item = this[i];
            if (a_item === item) {
                result = i;
                break;
            }
        }
        return result;
    }
}

// 最简单数组去重法 
function unique1(array){ 
    var n = []; //一个新的临时数组 
    //遍历当前数组 
   for(var i = 0; i < array.length; i++){ 
       //如果当前数组的第i已经保存进了临时数组,那么跳过, 
       //否则把当前项push到临时数组里面 
       if (n.indexOf(array[i]) == -1) n.push(array[i]); 
   } 
   return n; 
}

对象键值对法

该方法执行的速度比其他任何方法都快, 就是占用的内存大一些,实现思路:新建一js对象以及新数组,遍历传入数组时,判断值是否为js对象的键,不是的话给对象新增该键并放入新数组。注意 点: 判断是否为js对象键时,会自动对传入的键执行“toString()”,不同的键可能会被误认为一样;例如: a[1]、a["1"] 。解决上述问题还是得调用“indexOf”。

// 速度最快, 占空间最多(空间换时间) 
function unique2(array) {
    var n = {}, r = [], len = array.length, val, type;
    for (var i = 0; i < array.length; i++) {
        val = array[i];
        type = typeof val;
        if (!n[val]) {
            n[val] = [type];
            r.push(val);
        } else if (n[val].indexOf(type) < 0) {
            n[val].push(type);
            r.push(val);
        }
    }
    return r;
}

.数组下标判断法

还是得调用“indexOf”性能跟方法1差不多,实现思路:如果当前数组的第i项在当前数组中第一次出现的位置不是i,那么表示第i项是重复的,忽略掉。否则存入结果数组。

function unique3(array) {
    var n = [array[0]];
    //结果数组 
    //从第二项开始遍历 
    for (var i = 1; i < array.length; i++) {
        //如果当前数组的第i项在当前数组中第一次出现的位置不是i, 
        //那么表示第i项是重复的,忽略掉。否则存入结果数组 
        if (array.indexOf(array[i]) == i)
            n.push(array[i]);
    }
    return n;
}

4.排序后相邻去除法

虽然原生数组的”sort”方法排序结果不怎么靠谱,但在不注重顺序的去重里该缺点毫无影响。实现思路:给传入数组排序,排序后相同值相邻,然后遍历时新数组只加入不与前一值重复的值。

// 将相同的值相邻,然后遍历去除重复值 
function unique4(array) {
    array.sort();
    var re = [array[0]];
    for (var i = 1; i < array.length; i++) {
        if (array[i] !== re[re.length - 1]) {
            re.push(array[i]);
        }
    }
    return re;
}

优化遍历数组法

该方法的实现代码相当酷炫,实现思路:获取没重复的最右一值放入新数组。(检测到有重复值时终止当前循环同时进入顶层循环的下一轮判断)推荐

var arr = [2,2,4,3,3,4]

// 思路:获取没重复的最右一值放入新数组 
function unique5(array) {
    var r = [];
    for (var i = 0, l = array.length; i < l; i++) {
        for (var j = i + 1; j < l; j++)
            if (array[i] === array[j])
                j = ++i;
        r.push(array[i]);
    }
    return r;
}

unique5(arr)

 IE9以下不支持indexOf()

// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {

    var k;

    // 1. Let O be the result of calling ToObject passing
    //    the this value as the argument.
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }

    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get
    //    internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If len is 0, return -1.
    if (len === 0) {
      return -1;
    }

    // 5. If argument fromIndex was passed let n be
    //    ToInteger(fromIndex); else let n be 0.
    var n = +fromIndex || 0;

    if (Math.abs(n) === Infinity) {
      n = 0;
    }

    // 6. If n >= len, return -1.
    if (n >= len) {
      return -1;
    }

    // 7. If n >= 0, then Let k be n.
    // 8. Else, n<0, Let k be len - abs(n).
    //    If k is less than 0, then let k be 0.
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

    // 9. Repeat, while k < len
    while (k < len) {
      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the
      //    HasProperty internal method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      //    i.  Let elementK be the result of calling the Get
      //        internal method of O with the argument ToString(k).
      //   ii.  Let same be the result of applying the
      //        Strict Equality Comparison Algorithm to
      //        searchElement and elementK.
      //  iii.  If same is true, return k.
      if (k in O && O[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}
原文地址:https://www.cnblogs.com/hupan508/p/7059290.html