JavaScript array de-weight 6 ways

Source: Internet
Author: User
Tags array length javascript array

Array de-weight involves a lot of basic knowledge, summed up the following 6 methods:
    1. Double for loop, push new array;

    2. Double for loop, splice original array;

    3. Single for loop, traversing object properties;

    4. A single for loop, sort after the traversal;

    5. Es5,indexof, positioning to go heavy;

    6. ES6, ... and set methods.

1, double-loop, if the same value is skipped, not the same will push into the new array
1Array.prototype.distinct1 =function(){2     vararr = This,3 I,j,4Len =Arr.length,5result = [];6 7      for(i = 0; i < Len; i++){8          for(j = i + 1; j < Len; J + + ){9             if(Arr[i] = = = Arr[j]) {//determine if there are equal itemsTenj = ++i;//perform a bounce inside loop i = i+1; j=i; One             } A         } - Result.push (Arr[i]); -     } the     returnresult; - }; - varARR1 = [1, 1, ' 1 ', ' 1 ',true,true, ' true ', ' true ']; -Console.log (Arr1.distinct1 ())//returns [1, "1", True, "true"]

2. Double loop, delete operation on original array (splice)
1Array.prototype.distinct2 =function () {2     vararr = This,3 I,4 J,5Len =arr.length;6      for(i = 0; i < Len; i++){7          for(j = i + 1; j < Len; J + +){8             if(Arr[i] = = =Arr[j]) {9Arr.splice (j,1);//to remove it after judgingTenlen--;//The original array length minus 1 Onej--;//Internal Loop index minus 1 A             } -         } -     } the     returnarr; - };  - varARR2 = [1, 1, ' 1 ', ' 1 ',true,true, ' true ', ' true ']; -Console.log (Arr2.distinct2 ());//[1, "1", True, "true"]
3, Object properties, using object property names can not be the same, traversing the array, using the Obj object to save the array value
1 //determines whether the array value has been saved in obj, is not saved, is push to a new array and saved with the Obj[arr[i]]=1 record2ARRAY.PROTOTYPE.DISTINCT3 =function (){ 3     vararr = This,4 I,5result = [],6obj = {},7Len =arr.length;8      for(i = 0; i < Len; i++){9         if(!obj[arr[i]]) {//if obj[arr[i]] = = False, which is not found in obj Arr[i] PropertyTenObj[arr[i]] = 1;//assigning values to object properties One Result.push (Arr[i]); A         } -     } -     returnresult;  the }; -  - varARR3 = [1, 1, ' 1 ', ' 1 ',true,true, ' true ', ' true ']; - Console.log (Arr3.distinct3 ()); //[1, True], object properties call the ToString () method by default and need to be optimized

4. Sort (), sorts the array, and then invokes the for loop once
1Array.prototype.distinct4 =function (){2     vararr = This,3 I,4Len =arr.length;5Arr.sort ();//Sort incoming Array6     varNarr = [arr[0]];//Initializes a new array with arr[0]7      for(i = 0; i < Len; i++){8         if(Arr[i]!== narr[narr.length-1]) {//compare to the new array from the last item forward9 Narr.push (Arr[i]);Ten         } One     } A     returnNarr; - }; - varARR4 = [1, 1, ' 1 ', ' 1 ',true,true, ' true ', ' true ']; theConsole.log (Arr4.distinct4 ());//[1, "1", True, "true"]

5, IndexOf () Location lookup compatible IE8 indexOf () method
1Array.prototype.forEach = Array.prototype.forEach | |function(callback, Thisarg) {2     if(!callback | |typeofCallback!== ' function ')return;3 4      for(vari = 0, j = This. length; I < J; i++) {5Callback.call (Thisarg, This[i], I, This);6     }7}
Compatible with the IE8 ForEach () method
1Array.prototype.forEach = Array.prototype.forEach | |function(callback, Thisarg) {2     if(!callback | |typeofCallback!== ' function ')return;3 4      for(vari = 0, j = This. length; I < J; i++) {5Callback.call (Thisarg, This[i], I, This);6     }7}
5.1 indexOf () for loop once
1Array.prototype.distinct5_1 =function (){2     vararr = This,3result = [],4 I,5Len =arr.length;6 7      for(vari = 0; i < Len; i++) {8         if(Result.indexof (arr[i]) = = = 1) {9 Result.push (Arr[i]);Ten         } One     } A     returnresult; -};
5.2 IndexOf () in conjunction with ForEach (), the original array starts with item I, with only one
1Array.prototype.distinct5_2 =function (){2     vararr = This,3result = [] ;4Arr.foreach (function(E, I, arr) {5         if(Arr.indexof (e) = = = i) {//IndexOf Determines whether the value of an element is equal to the current index6 Result.push (e);7         }8     });9 Ten     returnresult; One};

5.3 indexOf () combined with ForEach (), the original array of item I is compared to section i+1, and no rebate 1 is found.
1Array.prototype.distinct5_3 =function (){2     vararr = This,3result = [],4Len =arr.length;5Arr.foreach (function(E, I, arr) {//The Map,filter method can also be used here to achieve6         varBOOL = Arr.indexof (e,i+1);//start looking for duplicates from the next index value passed in the parameter7             if(bool = = =-1){8 Result.push (e);9             }Ten     }); One     returnresult; A};

1 var = [Arr5, ' 1 ', ' 1 ',true,true, ' true ', ' true ']; 2 // [1, "1", True, "true"] 3 Console.log (Arr5.distinct5_2 ()); 4 Console.log (Arr5.distinct5_3 ());

6.es6 ... Set ()
1 var = [Arr6, ' 1 ', ' 1 ',true,true, ' true ', ' true ']; 2 var arr=[... New Set (arr)]; 3 console.log (arr);             // [1, "1", True, "true"]

  Summary, go to heavy method many, personal suggestion direct fifth method, running efficiency will be higher, but ES6 method is more simple domineering; These 6 methods are only JS source code, in the development work is often seen in the package is good, but the foundation is to be compacted, in order to deal with the front-end frame update so fast rhythm, easy to get started ... Please correct me.

Original articles, reproduced annotated source.

  

JavaScript array de-weight 6 ways

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.