In some background languages, several methods are built in to handle duplicate data in arrays or collections. But there is no similar method in JS, there are some methods on the Internet, but not enough detail. Some of the code comes from the network. The individual totals are as follows: There are roughly 4 ways
1) Use two cycles to compare the original notation
Easy to understand efficiency is relatively low
1Array.prototype.unique1 =function () {2 varres = [ This[0]]//result Array3 for(vari = 1; I < This. length; i++) {4 varrepeat =false;5 for(varj = 0; J < Res.length; J + +) {6 if(Res[j] = =Res[i]) {7repeat =true8 Break9 }Ten } One if(!repeat) { A //do not repeat the push result array -Res.push ( This[i]) - } the } - returnRes -}
View Code
2) after sorting, compare adjacent positions for equality, if equal to push to result array
1Array.prototype.unique2 =function () {2 This. Sort ();3 varres = [ This[0]];4 for(vari = 1; I < This. length; i++) {5 if( This[i]!== res[res.length-1]) {6Res.push ( This[i]);7 }8 }9 returnRes;Ten}
View Code
3) Use IndexOf to determine if the element exists indexOf because it will also traverse once, so, not recommended
IndexOf
A the position of the first occurrence of a specified string value in the string.
The string value retrieved by B does not appear, then the method returns-1.
1 //1)2Array.prototype.unique3 =function () {3 varres = [ This[0]]//result Array4 for(vari = 1; I < This. length; i++) {5 if(Res.indexof ( This[i]) = =-1) n.push ( This[i]);6 }7 returnRes8 }9 //2)TenArray.prototype.unique4 =function () { One varres = [ This[0]] A for(vari = 1; I < This. length; i++) - if( This. IndexOf ( This[i]) = = i) N.push ( This[i]) - } the returnRes -}
View Code
4) Use object same-over property to detect high efficiency, but relatively high memory (space change time) recommended
1Array.prototype.unique5 =function () {2 varobj = {}3 varres = []4 for(vari = 0; I < This. length; i++)5 if(!obj[ This[i]]) {6Res.push ( This[i])7obj[ This] = 18 }9 }Ten returnRes One}
View Code
If there is a good way to welcome the supplement
Several ways to weigh JS array