zoukankan      html  css  js  c++  java
  • 数组去重

    数组去重总归不能避免数组中各个参数之间的比较,可以使用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]
  • 相关阅读:
    Linux分区
    Vim 基本配置
    Ubuntu几种常见乱码解决方法
    ADB
    ubuntu下安装配置ADB
    Tinyos学习笔记(三)
    Tinyos学习笔记(二)
    Codeforces Round #249 (Div. 2) A题
    poj 2007 Scrambled Polygon(极角排序)
    MemSQL Start[c]UP 2.0
  • 原文地址:https://www.cnblogs.com/tisikcci/p/5878910.html
Copyright © 2011-2022 走看看