Array deduplication is a common requirement. We will temporarily consider deduplication of arrays of the same type. The main thing is to clarify ideas and consider performance. The following methods are basically available on the Internet. Here is just a brief summary.
Things:
1. Traverse the array and compare one by one. If the comparison is the same, delete the following
2. Traverse the array, compare them one by one, and skip the previous duplicates if they are the same. If they are not the same, put them into the new array
3. Take any array element and put it into the new array, traverse the remaining array elements, take any one, compare it one by one with the elements of the new array, if there are differences, put it into the new array.
4. Traverse the array, take an element as an attribute of the object, and determine whether the attribute exists
1. Delete the following duplicates:
function ov1(arr){ //var a1=((new Date).getTime()) for(var i=0;i<arr.length;i++) for(var j=i+1;j<arr.length;j++) if(arr[i]===arr[j]){arr.splice(j,1);j--;} //console.info((new Date).getTime()-a1) return arr.sort(function(a,b){return a-b}); }
2. This is a conventional method, which is easier to understand. If they are the same, jump out of the loop
function ov2(a) { //var a1=((new Date).getTime()) var b = [], n = a.length, i, j; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) if (a[i] === a[j]){j=false;break;} if(j)b.push(a[i]); } //console.info((new Date).getTime()-a1) 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 ov3(a) { //var a1=((new Date).getTime()) var b = [], n = a.length, i, j; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) if (a[i] === a[j])j=++i b.push(a[i]);} //console.info((new Date).getTime()-a1) return b.sort(function(a,b){return a-b}); }
4. Ensure that everything in the new array is unique
function ov4(ar){ //var a1=((new Date).getTime()) var m=[],f; for(var i=0;i<ar.length;i++){ f=true; for(var j=0;j<m.length;j++) if(ar[i]===m[j]){f=false;break;}; if(f)m.push(ar[i])} //console.info((new Date).getTime()-a1) return m.sort(function(a,b){return a-b}); }
5. Use object attributes
function ov5(ar){ // var a1=(new Date).getTime() var m,n=[],o= {}; for (var i=0;(m= ar[i])!==undefined;i++) if (!o[m]){n.push(m);o[m]=true;} // console.info((new Date).getTime()-a1) return n.sort(function(a,b){return a-b});; }
The above recommended methods for removing duplicate values from JavaScript arrays are all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.