js实现数组去重的六种方法

方法一

使用数组的indexof方法,如果elementindex不相等则说明element相同,则过滤掉

Array.prototype.distinct1 = function () {
    
    
    return this.filter(function (element, index, self) {
    
    
        return self.indexOf(element) === index;
    });
}

方法二

ES6提供了数据结构Set。类似于数组,但是没有重复值。可以利用Set数据结构中值不能重复的特性去重

Array.prototype.distinct2 = function () {
    
    
    let set = new Set(this);
    return [...set];
}

方法三

遍历两个数组,将原数组的值和新数组的值一一进行比较,如果原数组的值不存在则加入新数组中

Array.prototype.distinct3 = function () {
    
    
    let result = [];
    for (let i of this) {
    
    
        let flag = 0;
        for (let j of result) {
    
    
            if (i === j) {
    
    
                flag = 1;
            }
        }
        if (flag === 0) {
    
    
            result.push(i);
        }
    }
    return result;    
}

方法四

先将数组进行排序,然后遍历数组,将数组中每个值与其后一个值比较,如果不同则存入新数组

Array.prototype.distinct4 = function () {
    
    
    var arr = this.sort();
    var result = [];
    for (let i = 0; i < arr.length; i++) {
    
    
        if (arr[i] != arr[i + 1])
            result.push(arr[i]);
    }
    return result;
}

方法五

js中数组也是对象,可以根据对象属性的特性。遍历数组,如果该值不是对象的属性,则在对象中添加等于该值的属性,并且同时把该值加入新数组

Array.prototype.distinct5 = function () {
    
    
    let result = [];
    let obj = {
    
    };
    for (let x of this) {
    
    
        if (!obj[x]) {
    
    
            obj[x] = x;
            result.push(x);
        }
    }
    return result;
}

方法六

双重循环遍历数组,如果值相同,使用splice方法删去后一个相同的值

Array.prototype.distinct6 = function () {
    
    
    let arr = this;
    for (let i = 0; i < arr.length; i++) {
    
    
        for (let j = i + 1; j < arr.length; j++) {
    
    
            if (arr[i] === arr[j]) {
    
    
                arr.splice(j, 1);
                j--;
            }
        }
    }
    return arr;
}

以上六种方法均可以实现数组去重,区别是性能不同,并且有的方法会改变数组的顺序。

猜你喜欢

转载自blog.csdn.net/younow22/article/details/113156586