js数组 去重复数据和取重复数据

 

 

方法一:去重复数据

<script>

Array.prototype.distinct=function(){

var a=[],b=[];

for(var prop in this){

   var d = this[prop];

   if (d===a[prop]) continue; //防止循环到prototype

   if (b[d]!=1){

    a.push(d);

    b[d]=1;

   }

}

return a;

}

var x=['a','b','c','d','b','a','e','a','b','c','d','b','a','e'];

document.write('原始数组:'+x);

document.write("<br />");

document.write('去重复后:'+x.distinct());

</script>

方法二:取重复数据

    <script type="text/javascript">

Array.prototype.distinct=function(){

   var a=[],b=[],c=[],d=[];

   for(var prop in this){

    var d = this[prop];

    if (d===a[prop])

    {

    continue;

    }//防止循环到prototype

    if (b[d]!=1){

     a.push(d);

     b[d]=1;

    }

    else {

  

     c.push(d);

     d[d]=1;

    }

   }

   //return a;

   return c.distinct1();

}

Array.prototype.distinct1=function(){

var a=[],b=[];

for(var prop in this){

   var d = this[prop];

   if (d===a[prop]) continue; //防止循环到prototype

   if (b[d]!=1){

    a.push(d);

    b[d]=1;

   }

}

return a;

}

var x=['a','b','c','d','b','a','e','a','b','c','d','b','a','e','f','f','g'];

document.write('原始数组:'+x);

document.write("<br />");

document.write('取得重复数据:'+x.distinct());

</script>

posted @ 2014-12-11 23:16  x_window  阅读(295)  评论(0)    收藏  举报