1. Using the properties of arrays
1. Iterate through the array, and also traverse the auxiliary array to find out whether there are the same items in the two arrays, and then push in if there is a break.
//first version array de-weightfunctionUnique (arr) {varres =[], Len=arr.length; for(Let i = 0;i < Len; i++){ varReslen =res.length; for(Let J = 0;j < Reslen; j + +) {//traversing auxiliary Arrays if(Arr[i] = = =Res[j]) { Break; } } if(J = =Reslen) {Res.push (arr[i]);//No, add it in . } } returnRes;}
2. Using Es5 's IndexOf method
// the second version of the array to ES5 syntax, IE8 can not be used function Unique (arr) { var len = arr.length, = []; for (Let i = 0; i < len; i++) { = arr[i]; if // no Return-1 found Res.push (Arr[i]); } } return Res;}
3. If the array is already sorted
function Unique (arr) { var len = arr.length; Last, = []; for (Let i = 0;i < Len; i++) { = arr[i]; if // Store the last value Res.push (val); } = val; } return Res;}
4. Leave an interface and pass a parameter to determine if the array is already sorted
functionUnique (arr, issort) {varLen =Arr.length, Res=[], last; if(Issort!== ' Boolean ') {Issort=false; } for(Let i = 0;i < Len; i++){ varval =Arr[i]; if(issort) {if(!i | | val!==Last ) {Res.push (val); } Last=Val; }Else{ if(Res.indexof (val) = = = 1) {Res.push (val); } } } returnRes;}
5. If there is a special need, leave an interface, more flexible
functionUnique (arr, Issort, fn) {varres =[], Len=Arr.length, NewArr=[], last; for(Let i = 0;i < Len; i++){ varval =arr[i], com= fn?fn (Val, I, arr): Val; if(issort) {if(!i | | com = = =Last ) {Res.push (val); } Last=com; }Else if(FN) {if(Newarr.indexof (com) = = = 1) {Newarr.push (COM); Res.push (Val); } }Else if(Res.indexof (val = = = 1) {Res.push (val); } } returnRes;}
6. Optimize with internal filter method
function Unique (arr) { var res = [], = Arr.filter (function(item, index, arr) { return res.indexof (item) = = = Index; // returns True if added to the array res, otherwise not added }); return Res;}
2. Use of object properties
1. The first method
function Unique (arr) { var obj = {}, = [], = Arr.filter (function (item, index, AEE) { returnfalsetrue); }); return Res}
Note: There is a bug,var = [1, 1, "1", 2], the number type is not recognized, and the string type is added to the object and is converted to a string.
2. The second method
function Unique (arr) { var obj = {}, = [], = arr.length; = Arr.filter (function (item, index, arr) { return obj.hasownproperty ( typeoffalse : (typeoftrue; }); return Res;}
Note: There are also bugs here, because the return type of typeof does not detect the object.
3. The third method
Use the JSON method to optimize.
function Unique (arr) { var obj = {}, = [], = arr.length; = Arr.filter (function (item, index, arr) { return obj.hasownproperty ( typeoffalse : (typeoftrue; }) return Res;}
The set () object in 3.ES6
function Unique (arr) { return [... New Set (arr)];}
JavaScript array de-weight method summary