Recently busy, no time to update the blog, and so busy will be finishing an article using Angularjs to build a medium-sized single-page application (SPA) articles, look forward to! Occupy a hole first.
There are many kinds of algorithms for array de-weight, the following is one.
Ideas are as follows:
- Defines an empty object, obj;
- Loop array arr, determine if Obj[arr[i]] is false, and if so, place the array element in result and set Obj[arr[i]] to true;
- Obj[arr[0]] "must be false, because obj is empty, arr[0] will be placed in result, and Obj[arr[0]] is set to true;
- In the process of looping, if any element (such as nth Element) and Arr[0] is the same, then Obj[arr[n]] will be the same as obj[arr[0]] (all true), because key is the same, value must be the same.
So we can go to the heavy.
The code is as follows:
1 functionUnique (arr) {2 varobj={};3 varresult=[];4 for(vari=0;i<arr.length;i++){5 if(!Obj[arr[i]]) {6 Result.push (Arr[i]);7obj[arr[i]]=true;8 }9 }Ten returnresult; One } A varArray = [32,12,4,27,12,9,20,32,12,8,44,18]; -Console.log (unique (array));
----------------------------------------------------------------------------------Gorgeous split-line----------------------- --------------------------------------------------------------
After writing, we found that there is a simpler array de-RE algorithm, using the array filter method, the following is the code:
1 function () {2 return this. Filter (function (V, I, m) {3 return i <= m.indexof (v ); 4 }); 5 }; 6 var array = [1,2,3,12,3,2,1,2,30]; 7 array.unique ();
Using JavaScript for Array de-weight-an efficient algorithm