Summary of common JavaScript array algorithms

Source: Internet
Author: User

Summary of common JavaScript array algorithms

Whether in the interview or in the written test, we are often asked about the JavaScript array of some algorithms, such as array de-weight, array intersection, array scrambling and so on. Take some time today to summarize some of the commonly used array algorithms in JavaScript in order to make it easier for you to interview the written test or the daily development process. Some of the algorithms come from the network, where the following summary is done. At the end of the article I will attach the source of reference, if the direct look at the algorithm is more boring can go to the reference to see, the explanation is very good.

1, the array to weight

Method 1:

1//IndexOf method using array 2 function unique (arr) {3   var result = []; 4 for   (var i = 0; i < arr.length; i++) 5   {6
   if (Result.indexof (arr[i]) = =-1) result.push (Arr[i]); 7   }8   return result;9}

Method 2:

1//Using the hash table, there may be errors like strings and numbers, such as var a = [1, 2, 3, 4, ' 3 ', 5], will return [1, 2, 3, 4, 5] 2 function unique (arr) 3 {4     var hash = {},result = [];  5 for     (var i = 0; i < arr.length; i++) 6     {7         if (!hash[arr[i])  8         {9             hash[arr[i]] = true; 10
   result.push (Arr[i]);         }12     }13     return result;14}

Method 3:

1//sorted after comparison adjacent, if the same is discarded, otherwise added to the result. There will be the same problem as Method 2, if there are 1, 1, ' 1 ' in the array, the error will be 2 function unique (arr) {3     arr.sort (); 4     var result=[arr[0]; 5     for (var i = 1; i < arr.length; i++) {6         if (Arr[i]!== arr[i-1]) {7             Result.push (Arr[i]); 8         } 9     }10< C21/>return result;11}

Method 4:

1//simplest but least efficient algorithm, there is no bug in Method 2 and Method 3 appears 2 function unique (arr) {3     if (arr.length = = 0) return; 4     var result = [Arr[0] ], isrepeate;  5 for     (var i = 0, j = arr.length; l < J; i++) {6         isrepeate = false; 7         for (var k = 0, H = result.length; k < H; k++) {8             if (result[k] = = = Arr[i]) {9                 isrepeate = true;10                 break;11             }12             if (k = = h) break;13         }14< C11/>if (!isrepeate) Result.push (Arr[i]);     }16     return result;17}

Method 5:

1//This method takes full advantage of recursion and indexof method, thanks Netizen @ true love like Blue 2 var unique = function (arr, NEWARR) {3      var num;4  5      if ( -1 = = Arr.index of (num = Arr.shift ())) Newarr.push (num); 6  7      arr.length && unique (arr, NEWARR); 8}

2. Array Order disturbance

Method 1:

1//each time a random number is drawn and moved into the new array 2 function shuffle (array) {3     var copy = [], 4         n = array.length, 5         i; 6     //If there are elements left, continue 。。。 7     while (n) {8         //random extraction of an element 9         i = Math.floor (Math.random () * array.length);         //If this element was not previously selected: One         if (i in array) {             Copy.push (array[i]);             Delete array[i];14             n--;15         }16     }

Method 2:

1//Similar to Method 1, except by splice to remove the original array has the option 2 function shuffle (array) {3     var copy = [], 4         n = array.length, 5         i; 6
   //If there are elements left. 7     while (n) {8         //Randomly Select an element 9         i = Math.floor (Math.random () * n--), or         move to a new array         Copy.push ( Array.splice (i, 1) [0]);     }13     return copy;14}

Method 3:

The front random number is followed by the number of the end of the exchange, followed by moving forward, that is: the first n number of randomly drawn a with the nth Exchange, the second n-1 number with the first n-1 exchange, and so on. function Shuffle (array) {    var m = array.length,        t, I;    If there are elements    left ... while (m) {        //random selection of an element        ... i = Math.floor (Math.random () * m--);        Swap with current element        t = array[m];        ARRAY[M] = Array[i];        Array[i] = t;    }    return array;}

3. Array judgment

Method 1:

1//Self-IsArray Method 2 var array6 = [];3 array.isarray (ARRAY6);//true

Method 2:

1//using instanceof operator 2 var array5 = [];3 array5 instanceof Array;//true

Method 3:

1//With toString return value 2 function IsArray (o) {3     return Object.prototype.toString.call (o) = = = ' [Object Array] '; 4}

4, array to find the intersection

Method 1:

1//using the filter and array of the IndexOf Method 2 Array1.filter (function (n) {3     return Array2.indexof (n)! =-14});

5. Array-Seeking and set

Method 1:

1//Method principle: Connect two arrays and go to weight 2 function arrayunique (array) {3     var a = Array.concat (); 4 for     (var i=0; i<a.length; ++i) {  5 for         (var j=i+1; j<a.length; ++j) {6             if (a[i] = = = A[j]) 7                 A.splice (J--, 1); 8         } 9     }10     return A;12};

6, array to find the difference set

Method 1:

1//using the filter and IndexOf Method 2 Array.prototype.diff = function (a) {3     return This.filter (function (i) {return a.indexof (i) < 0;}); 4};

The craved has been summarized for the time being and is awaiting further additions. You are welcome to add.

Summary of common JavaScript array algorithms

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.