Summary of common JavaScript array algorithms

  • 2020-12-19 20:55:25
  • OfStack

Today, I will take some time to summarize some common array algorithms in javascript, so that you can use them in the interview, written test or daily development. Part of the algorithm from the network, here to do the summary. At the end of the article, I will attach the reference source. If the algorithm is boring directly, you can go to the reference to see it. The explanation is very good.

1. Unload the array

Method 1:


// Using array indexOf methods 
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 hash table , Strings and numbers may appear 1 Make a mistake, e.g var a = [1, 2, 3, 4, '3', 5], Returns the [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:

// After sorting, it is relatively adjacent. If 1 sample is discarded, otherwise, it is added to result. The same problem occurs with method 21. If 1,1,'1' exists in the array, it will be sorted incorrectly


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 , There will be no method 2 And methods 3 The emergence of bug
function unique (arr) {
  if(arr.length == 0) return;
  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 approach takes full advantage of recursive sums indexOf Method, thank the net friend @ True love is like deep blue 
var unique = function (arr, newArr) {
   var num;

   if (-1 == arr.indexOf(num = arr.shift())) newArr.push(num);

   arr.length && unique(arr, newArr);
}

2. Array order confusion

Method 1:


// Each random draw 1 Number and move to the new array 
function shuffle(array) {
  var copy = [],
    n = array.length,
    i;
  //  If there are elements left, continue... 
  while (n) {
    //  A random sample 1 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:


// With the method 1 Similar, only through splice To remove the original array option 
function shuffle(array) {
  var copy = [],
    n = array.length,
    i;
  //  If there are elements left. 
  while (n) {
    //  Randomly selected 1 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 random number in front is swapped with the number at the end in turn, followed by moving forward in turn, namely: the 1 Before the time n Number random drawing 1 As the first n Student: An exchange, number one 2 Before the time n-1 With the first number n-1 Exchange, and so on. 
function shuffle(array) {

var m = array.length,
  t, i;
//  If there are elements left... 
while (m) {
  //  Randomly selected 1 Other elements... 
  i = Math.floor(Math.random() * m--);
  //  Exchange with the current element 
  t = array[m];
  array[m] = array[i];
  array[i] = t;
}
return array; }

3. Array judgment

Method 1:


// built-in isArray methods 
var array6 = [];
Array.isArray(array6 );//true

Method 2:


   // using instanceof The operator 
   var array5 = [];
   array5 instanceof Array;//true

Method 3:


// using hash table , Strings and numbers may appear 1 Make a mistake, e.g var a = [1, 2, 3, 4, '3', 5], Returns the [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;
}
0

4. Find the intersection of arrays

Method 1:


// using hash table , Strings and numbers may appear 1 Make a mistake, e.g var a = [1, 2, 3, 4, '3', 5], Returns the [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;
}
1

5. Find the union of arrays

Method 1:


// using hash table , Strings and numbers may appear 1 Make a mistake, e.g var a = [1, 2, 3, 4, '3', 5], Returns the [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;
}
2

6. Array differential set

Method 1:


   // using 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 1 array relative to another array, such as array1.diff (array2), can only find the difference set of array1 relative to array2, if you want to get both different values of the two arrays, you can use array1.diff (array2).concat (array2.diff (array1)), or you can use method 2

Method 2


// using hash table , Strings and numbers may appear 1 Make a mistake, e.g var a = [1, 2, 3, 4, '3', 5], Returns the [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;
}
4

This point is summarized temporarily and needs to be added later. Welcome to add, if you have any questions, please leave a message, discuss and progress together, ^_^


Related articles: