Home  >  Article  >  Web Front-end  >  Summary of commonly used array algorithms in JavaScript_javascript skills

Summary of commonly used array algorithms in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:15:49945browse

Take some time today to summarize some commonly used array algorithms in JavaScript, so that you can use them in written interviews or daily development processes. Some of the algorithms come from the Internet and are summarized here. I will attach the source of the reference at the end of the article. If it is boring to look at the algorithm directly, you can read it in the reference literature. The explanation is very good.

1. Array deduplication

Method 1:

//利用数组的indexOf方法
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:

//利用hash表,可能会出现字符串和数字一样的话出错,如var a = [1, 2, 3, 4, '3', 5],会返回[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:

//Compare adjacent items after sorting, if they are the same, give up, otherwise add to result. The same problem as method 2 will occur. If there are situations like 1,1,'1' in the array, troubleshooting will occur

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:

//最简单但是效率最低的算法,也不会出现方法2和方法3出现的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:

//此方法充分利用了递归和indexOf方法,感谢网友@真爱像深蓝
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 disruption

Method 1:

//每次随机抽一个数并移动到新数组中
function shuffle(array) {
  var copy = [],
    n = array.length,
    i;
  // 如果还剩有元素则继续。。。
  while (n) {
    // 随机抽取一个元素
    i = Math.floor(Math.random() * array.length);
    // 如果这个元素之前没有被选中过。。
    if (i in array) {
      copy.push(array[i]);
      delete array[i];
      n--;
    }
  }
  return copy;
};

Method 2:

//跟方法1类似,只不过通过splice来去掉原数组已选项
function shuffle(array) {
  var copy = [],
    n = array.length,
    i;
  // 如果还剩有元素。。
  while (n) {
    // 随机选取一个元素
    i = Math.floor(Math.random() * n--);
    // 移动到新数组中
    copy.push(array.splice(i, 1)[0]);
  }
  return copy;
}

Method 3:

//前面随机抽数依次跟末尾的数交换,后面依次前移,即:第一次前n个数随机抽一个跟第n个交换,第二次前n-1个数跟第n-1个交换,依次类推。
function shuffle(array) {

var m = array.length,
  t, i;
// 如果还剩有元素…
while (m) {
  // 随机选取一个元素…
  i = Math.floor(Math.random() * m--);
  // 与当前元素进行交换
  t = array[m];
  array[m] = array[i];
  array[i] = t;
}
return array; }

3. Array judgment

Method 1:

//自带的isArray方法
var array6 = [];
Array.isArray(array6 );//true

Method 2:

   //利用instanceof运算符
   var array5 = [];
   array5 instanceof Array;//true

Method 3:

   //利用toString的返回值
   function isArray(o) {
     return Object.prototype.toString.call(o) === '[object Array]'; 
   }

4. Find the intersection of arrays

Method 1:

   //利用filter和数组自带的indexOf方法
   array1.filter(function(n) {
   return array2.indexOf(n) != -1 });

5. Union of arrays

Method 1:

   //方法原理:连接两个数组并去重
   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;
   };

6. Array difference set

Method 1:

   //利用filter和indexOf方法
   Array.prototype.diff = function(a) {
     return this.filter(function(i) {
      return a.indexOf(i) < 0;
      });
};

The above method 1 can only find the difference between one array and another array. For example, array1.diff(array2) can only find the difference between array1 and array2. If you want to compare the different values ​​of the two arrays, To get it, you can array1.diff(array2).concat(array2.diff(array1)), or you can 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 );

This is summarized for now and will be added later. Welcome everyone to add. If you have any questions, please leave a message to discuss and make progress together. ^_^

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn