Array deduplication is a common requirement. We will temporarily consider repeated arrays of the same type. It mainly aims to clarify ideas and considerations.
Array deduplication is a common requirement. We will temporarily consider repeated arrays of the same type. It mainly aims to clarify the ideas and consider the performance. The following methods are available on the Internet. Here is a brief summary.
Ideas:
- Traverse the array, compare them one by one, and delete
- Traverse the array, compare them one by one, compare them to the same one, skip the previous duplicate, and put the different into the new array
- Take an array element and add it to the new array. traverse the remaining array elements and compare them with the elements of the new array. If there are different elements, add them to the new array.
- Traverse the array and take an element as the object attribute to determine whether the attribute exists.
1. Delete the following duplicate:
Function ov1 (arr) {// var a1 = (new Date). getTime () for (var I = 0; I2. This is a conventional method and is easy to understand. If the same method is used, the loop jumps out.
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 like 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 the new array is unique.
Function ov4 (ar) {// var a1 = (new Date). getTime () var m = [], f; for (var I = 0; I5. 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});;}Address of this article: http://www.nowamagic.net/librarys/veda/detail/1487,welcome.