JS array to reload and fetch the sample code

  • 2020-03-30 01:25:36
  • OfStack

Method 1: repeat the data

<script>
Array.prototype.distinct=function(){
var a=[],b=[];
for(var prop in this){
   var d = this[prop];
   if (d===a[prop]) continue; //Prevent looping to 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(' The original array :'+x);
document.write("<br />");
document.write(' To repeat the :'+x.distinct());
</script>

Method 2: take duplicate data

<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;
    }//Prevent looping to 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; //Prevent looping to 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(' The original array :'+x);
document.write("<br />");
document.write(' To repeat the :'+x.distinct());
</script>

Related articles: