JavaScript Common array algorithm summary _javascript skill

Source: Internet
Author: User
Tags diff shuffle

Take some time today to summarize some of the most commonly used array algorithms in JavaScript to make it easier for you to interview written papers or use them in your daily development process. Some of these algorithms come from the network, here do the following summary collation. The end of the article I will refer to the source, if the direct look at the algorithm is more boring can go to the reference literature to see, explained very good.

One, the array to heavy

Method 1:

The IndexOf method of array is used to
function unique (arr) {
 var result = []; 
 for (var i = 0; i < arr.length i++)
 {
  if (Result.indexof (arr[i)) = = 1) result.push (arr[i));
 return result;
}

Method 2:

Using a hash table, there may be errors like string and number, such as var a = [1, 2, 3, 4, ' 3 ', 5], which returns [1, 2, 3, 4, 5]
function unique (arr) {
  var hash = { },result = []; 
  for (var i = 0; i < arr.length i++)
  {
    if (!hash[arr[i]]) 
    {
      Hash[arr[i]] = true; 
      Result.push (Arr[i]); 
    }
  return result;
}

Method 3:

The sort is next to each other, if the same is given up, otherwise add to result. There will be a problem like Method 2, if there are 1, 1, ' 1 ' in the array, it will be wrong

function Unique (arr) {
  arr.sort ();
  var result=[arr[0]];
  for (var i = 1; i < arr.length i++) {
    if (Arr[i]!== arr[i-1]) {
      Result.push (arr[i));
    }
  return result;
}

Method 4:

The simplest but least efficient algorithm does not appear with the bug
function unique (arr) {
  if (arr.length = 0)
  return that appears in Method 2 and Method 3. var result = [Arr[0]], isrepeate;
  for (var i = 0, j = arr.length I < J; i++) {
    isrepeate = false;
    for (var k = 0, H = result.length k < h; k++) {
      if (result[k] = = Arr[i]) {
        isrepeate = true;
        break;
      if (k = = h) break;
    }
    if (!isrepeate) Result.push (Arr[i]);
  }
  return result;
}

Method 5:

This method took full advantage of recursion and indexof method, thanks to netizens @ true love like dark blue
var unique = function (arr, newArr) {
   var num;

   if ( -1 = = arr.indexof (num = Arr.shift ())) Newarr.push (num);

   Arr.length && Unique (arr, newArr);
}

Second, array order disturb

Method 1:

Draw a random number each time and move to the new array
function shuffle (array) {
  var copy = [],
    n = array.length,
    i;
  If there are elements left, continue ... While
  (n) {
    //randomly extracts an element
    i = Math.floor (Math.random () * array.length);
    If this element has not been selected before ...
    if (i in array) {
      Copy.push (array[i]);
      Delete Array[i];
      n--
    }
  }
  return copy;

Method 2:

Similar to Method 1, except by splice to remove the original array has option
function shuffle (array) {
  var copy = [],
    n = array.length,
    i;
  If there are elements left. While
  (n) {
    //randomly Select an element
    i = Math.floor (Math.random () * n--);
    Move to the new array
    Copy.push (Array.splice (i, 1) [0]);
  }
  return copy;
}

Method 3:

The first random number of numbers in turn with the end of the exchange, followed by the move forward, that is: the initial n number of a random draw with the nth Exchange, the second before the number of n-1 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) {
  //randomly Select an element ...
  i = Math.floor (Math.random () * m--);
  Exchange with the current element
  t = array[m];
  ARRAY[M] = Array[i];
  Array[i] = t;
}
return array; }

Three, array judgment

Method 1:

Self-IsArray method
var array6 = [];
Array.isarray (ARRAY6);//true

Method 2:

   Using the instanceof operator
   var array5 = [];
   Array5 instanceof Array;//true

Method 3:

   Use the return value of toString
   function IsArray (o) {returns
     Object.prototype.toString.call (o) = = ' [Object Array] '; 
   }

Four, array intersection

Method 1:

   Using filter and array IndexOf method
   Array1.filter (function (n) {return
   array2.indexof (n)!=-1});

Five, the collection of array

Method 1:

   Method principle: Connect two arrays and go to heavy
   function Arrayunique (array) {
     var a = Array.concat (array2);
     For (Var i=0. i<a.length; ++i) {for
       (var j=i+1; j<a.length; ++j) {
         if (a[i] = = A[j])
           A.splice (J--, 1) ;
       }
     }
     return A;
   };

Six, the array to seek the difference set

Method 1:

   Using the filter and IndexOf methods
   Array.prototype.diff = function (a) {return
     this.filter (function (i) {return
      A.indexof (i) < 0;
      });

The above Method 1 can only find the difference set of an array relative to another array, such as Array1.diff (Array2), can only find array1 relative array2 difference set, if you want to get two different values are obtained, you can Array1.diff (array2). Concat (Array2.diff (array1)), you can also use Method 2

Method 2

   var array1 = new Array (55,55,88,6,68,109,55,33,6,2,1);
   var array2 = [55,88,99,69,109,55,33,6,2,1];
   var Diffarr = Array1.concat (array2);
   
   var diff = Diffarr.filter (function (i) {return
           array1.indexof (i) < 0| | Array2.indexof (i) < 0;
       });
   
   Console.log (diff);

A summary of this is now pending further additions. Welcome everyone to add, if there is a problem, please leave a message, together to explore and progress, ^_^

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.