<! DOCTYPEhtml>      
<html lang="en">      
<head>    
    <title>Js array to achieve the algorithm</title>      
</head>      
<body>      
<script>      
    // Two for loops
    Array.prototype.unique1 = function() {      
        var res = [this[0]].for(var i = 1; i < this.length; i++){      
            var repeat = false;      
            for(var j = 0; j < res.length; j++){      
                if(this[i] === res[j]){      
                    repeat = true;      
                    break; }}if(! repeat){ res.push(this[i]); }}return res;      
    };      
    var arr = [0.0.1.2.3.4.5.6.7.8.9.10.6.'1'];      
    console.log(arr.unique1());      

    //indexOf
    Array.prototype.unique1s = function() {      
        var res = [this[0]].for(var i = 1; i < this.length; i++){        
            if(res.indexOf(this[i]) == -1){      
                res.push(this[i]); }}return res;      
    };      
    var arr = [0.0.1.2.3.4.5.6.7.8.9.10.6.'1'];      
    console.log(arr.unique1s());  
      
      
    // Use an empty object, only need a for loop, high efficiency (can not distinguish 1 from '1')
    Array.prototype.unique2 = function(){      
        var res = [];      
        var json = {};      
        for(var i = 0; i < this.length; i++){      
            if(! json[this[i]]){      
                res.push(this[i]);      
                json[this[i]] = 1; }}return res;      
    };      
    
    // Can distinguish 1 from '1'
    function unique3(array){     
        var n = {}, r = [], len = array.length, val, type;     
        for (var i = 0; i < array.length; i++) {     
            val = array[i];     
            type = typeof val;     
            if(! n[val]) { n[val] = [type]; r.push(val); }else if (n[val].indexOf(type) < 0) { n[val].push(type); r.push(val); }}return r;     
    }            
      
    var arr = [0.0.1.2.3.4.5.6.7.8.9.10.6.'1'];      
    console.log(arr.unique2());      
    
    var arr = [0.0.1.2.3.4.5.6.7.8.9.10.6.'1'];      
    console.log(unique3(arr));      

    // The new Set provided by ES6 can also be de-duplicated
    var items = new Set(arr);
    console.log(Array.from(items)); 
</script>      
</body>      
</html> 
Copy the code




\

\

\

\