javascript array deduplication is a relatively common requirement, and there are many solutions
Thoughts:
Traverse the array, compare one by one, delete the following if the comparison is the same
Traverse the array, compare one by one, compare the same, skip the previous duplicates, and put the different ones into the new array
Put any array element into the new array, traverse the remaining array elements, select any one, compare it one by one with the elements of the new array, if there are differences, put it into the new array.
Traverse the array, take an element, use it as an attribute of the object, and determine whether the attribute exists
1. Delete the following duplicates:
function ov(arr){ //var a=((new Date).getTime()) for(var i=;i<arr.length;i++) for(var j=i+;j<arr.length;j++) if(arr[i]===arr[j]){arr.splice(j,);j--;} //console.info((new Date).getTime()-a) return arr.sort(function(a,b){return a-b}); }
2. This is a conventional method, easier to understand. If they are the same, jump out of the loop
function ov(a) { //var a=((new Date).getTime()) var b = [], n = a.length, i, j; for (i = ; i < n; i++) { for (j = i + ; j < n; j++) if (a[i] === a[j]){j=false;break;} if(j)b.push(a[i]); } //console.info((new Date).getTime()-a) return b.sort(function(a,b){return a-b}); }
3. It took me a long time to understand this. Although the j loop continues here, the i value has changed. It is equivalent to a new i loop:
##
function ov(a) { //var a=((new Date).getTime()) var b = [], n = a.length, i, j; for (i = ; i < n; i++) { for (j = i + ; j < n; j++) if (a[i] === a[j])j=++i b.push(a[i]);} //console.info((new Date).getTime()-a) return b.sort(function(a,b){return a-b}); }
4. Ensure that everything in the new array is unique
function ov(ar){ //var a=((new Date).getTime()) var m=[],f; for(var i=;i<ar.length;i++){ f=true; for(var j=;j<m.length;j++) if(ar[i]===m[j]){f=false;break;}; if(f)m.push(ar[i])} //console.info((new Date).getTime()-a) return m.sort(function(a,b){return a-b}); }
5. Use object properties
function ov(ar){ // var a=(new Date).getTime() var m,n=[],o= {}; for (var i=;(m= ar[i])!==undefined;i++) if (!o[m]){n.push(m);o[m]=true;} // console.info((new Date).getTime()-a) return n.sort(function(a,b){return a-b});; }
The above is the detailed content of Detailed explanation of ideas and implementation code for removing duplicate elements from JavaScript arrays. For more information, please follow other related articles on the PHP Chinese website!