首页 > 技术文章 > 数组去重

tisikcci 2016-09-17 15:33 原文

数组去重总归不能避免数组中各个参数之间的比较,可以使用ES5中的 indexOf() 或者 sort() 方法来实现。

具体实现:

1. 判定临时数据 arr 中有没有指定参数,没有的话将其 push 进去。

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

实例:

        var arr1 = [1,2,3,5,1,2,3,5,1,2,8,9];
        console.log(arr1);//[1, 2, 3, 5, 1, 2, 3, 5, 1, 2, 8, 9]
        console.log(arr1.unique());//[1, 2, 3, 5, 8, 9]

 

2. 如果对最终结果的参数顺序没有要求,可以使用 sort(),排序后判定相邻两项是否相同,不同的话 push 到新数组中。

        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 arr1 = [1,2,3,5,1,2,3,5,1,2,8,9];
        console.log(arr1);//[1, 2, 3, 5, 1, 2, 3, 5, 1, 2, 8, 9]
        console.log(arr1.unique());//[1, 2, 3, 5, 8, 9]

 

推荐阅读