js array to achieve weight

Act One:

Create a new temporary array to hold the elements already in the array, indexOf () can iterate

var A = new new the Array (1,2,2,2,2,5,3,2,9,5,6,3 ); 
Array.prototype.unique1 = function () {
     var n-= [];      // a new temporary array 
    for ( var i = 0; i < the this .length; i ++ ) {
         // if the current i of the array has been saved into the temporary array is skipped 
        IF (n.indexOf ( the this [i]) -1 == ) { 
            n.push ( the this [I]); 
        } 
    } 
    return n-; 
} 
the console.log (a.unique1 ());

Act II:

Use hash table to store existing elements

= Array.prototype.unique2 function () {
     var the hash = {}, 
        n- = [];      // the hash as a hash table, n is a temporary array 
    for ( var I = 0; I < the this .length; I ++ ) {
         IF (! hash [ the this [I]]) {          // If the hash table entry is not the current 
            hash [ the this [I]] = to true ;    // stored hash table 
            n.push ( the this [I]);         // current element push the temporary array 
        } 
    } 
    return n-; 
}

Act III:

IndexOf position determination using array element first appears is the current position, indexOf () can iterate

= Array.prototype.unique3 function () {
     var n-= [ the this [0 ]]; 
     for ( var I =. 1; I < the this .length; I ++)     // from the second traversing 
    {
         // if the current array element the first position is not present in the array I 
        // note is repeated element 
        IF ( the this .indexOf ( the this [I]) == I) { 
            n.push ( the this [I]); 
        } 
    } 
    return n-; 
}

Act Four:

First go to re-sort

Array.prototype.unique4 = function(){
    this.sort(function(a, b){ return a - b;});
    var n = [this[0]];
    for(var i=1; i<this.length; i++){
        if(this[i] != this[i-1]){
            n.push(this[i]);
        }
    }
    return n;
}

 

Guess you like

Origin www.cnblogs.com/haohao-a/p/10960939.html