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+'<br/>'+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+'<br/>'+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!