Home  >  Article  >  Web Front-end  >  Detailed explanation of how to remove duplicate code from an array using JavaScript

Detailed explanation of how to remove duplicate code from an array using JavaScript

伊谢尔伦
伊谢尔伦Original
2017-07-22 14:46:511146browse

Remove duplication from array

Simple method to remove duplication: first declare an empty array, insert the repeated array in a for loop, and skip the non-duplicate insertion

var arr = [];  
for(var i=0;i<20;i++){  
    arr.push(parseInt(Math.random()*10));  
}  
Array.prototype.indexOf = function(n){  
    for(var i=0;i<this.length;i++){  
        if(this[i] == n){  
            return i;  
        }  
    }  
    return -1;  
}  
function removeDup(arr){  
    var result = [];  
    for(var i=0;i<arr.length;i++){  
        if(result.indexOf(arr[i]) == -1){  
            result.push(arr[i]);  
        }  
    }  
    return result;   
}  
var arr2 = removeDup(arr)  
document.write(arr+&#39;<br/>&#39;+arr2)

Algorithm Array Remove Duplication

var arr = [];  
for(var i=0;i<20;i++){  
    arr.push(parseInt(Math.random()*10));  
}  
Array.prototype.indexOf = function(n){  
    for(var i=0;i<this.length;i++){  
        if(this[i] == n){  
            return i;  
        }  
    }  
    return -1;  
}  
function removeDup(arr,s,e){  
    if(s==e){  
        //分割就剩下一个  
        return [arr[s]]  
    }else if(s==e-1){  
        //为了优化 剩下两个就不用分割啦  
        if(arr[s]==arr[e]){  
            return [arr[s]]  
        }else{  
            return [arr[s],arr[e]];  
        }  
    }  
    //数组平分成两段,  
    var l = Math.floor((s+e)/2);  
    //左边  
    var arrL = removeDup(arr,s,l);  
    //右边  
    var arrR = removeDup(arr,l+1,e);  
    //结果 先把左边的复制进去  
    var result = arrL;  
    //循环 将不重复的数据插入到结果里面  
    for(var i=0;i<arrR.length;i++){  
        if(result.indexOf(arrR[i])== -1 ) result.push(arrR[i])  
    }  
    return result; //返回结果  
}  
var arrDup = removeDup(arr, 0, arr.length-1);  
document.write(arr+&#39;<br/>&#39;+arrDup);

Explanation:Cut the duplicate array until only one data or two arrays are left at the end, and put the left data into the result Inside, the right side is repeatedly skipped without repeated insertion until the loop is completed and the result is returned

The above is the detailed content of Detailed explanation of how to remove duplicate code from an array using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn