Array de-duplication is a common requirement, we temporarily consider the same type of array to repeat. It is mainly to clarify the thinking and consider the performance. The following methods, basic online, here is simply a summary.
Ideas:
- Iterate over the array, compare each, compare to the same to delete the later Tuanfeng County University
- Iterate over the array, compare each, compare to the same, skip the previous duplicate, and put the new array in a different way
- Either takes an array element into the new array, iterates over the remaining array elements, and compares them with the elements of the new array, and if there is a different one, put the new array.
- Iterate through an array, take an element, act as an object's property, and determine whether a property exists
1. Delete the following duplicates:
View Source print?
2 |
//var a1=((new Date).getTime()) |
3 |
for ( var i=0;i<arr.length;i++) |
4 |
for ( var j=i+1;j<arr.length;j++) |
5 |
if (arr[i]===arr[j]){arr.splice(j,1);j--;} |
6 |
//console.info((new Date).getTime()-a1) |
7 |
return arr.sort( function (a,b){ return a-b}); |
2. This is a conventional method, better understanding, if the same jump out of the loop
View Source print?
02 |
//var a1=((new Date).getTime()) |
03 |
var b = [], n = a.length, i, j; |
04 |
for (i = 0; i < n; i++) { |
05 |
for (j = i + 1; j < n; j++) |
06 |
if (a[i] === a[j]){j= false ; break ;} |
09 |
//console.info((new Date).getTime()-a1) |
10 |
return b.sort( function (a,b){ return a-b}); |
3. It took me a long time to understand that the J Loop continues, but the I value has changed. is equal to a new I loop:
View Source print?
02 |
//var a1=((new Date).getTime()) |
03 |
var b = [], n = a.length, i, j; |
04 |
for (i = 0; i < n; i++) { |
05 |
for (j = i + 1; j < n; j++) |
06 |
if (a[i] === a[j])j=++i |
08 |
//console.info((new Date).getTime()-a1) |
09 |
return b.sort( function (a,b){ return a-b}); |
4. Ensure that the new array is unique
View Source print?
02 |
//var a1=((new Date).getTime()) |
04 |
for ( var i=0;i<ar.length;i++){ |
06 |
for ( var j=0;j<m.length;j++) |
07 |
if (ar[i]===m[j]){f= false ; break ;}; |
09 |
//console.info((new Date).getTime()-a1) |
10 |
return m.sort( function (a,b){ return a-b}); |
5. Using Object properties
View Source print?
2 |
// var a1=(new Date).getTime() |
4 |
for ( var i=0;(m= ar[i])!==undefined;i++) |
5 |
if (!o[m]){n.push(m);o[m]= true ;} |
6 |
// console.info((new Date).getTime()-a1) |
7 |
return n.sort( function (a,b){ return a-b});; |
A method of removing duplicate values from several arrays of JavaScript