The javascript array to duplicate the method summary

  • 2020-06-01 08:14:41
  • OfStack

The javascript array to duplicate the method summary


Array.prototype.unique1 = function () {
 var n = []; //1 Two new temporary arrays 
 for (var i = 0; i < this.length; i++) // Traverses the current array 
 {
  // If the current array is the first i I've saved it into a temporary array, so I'm gonna skip, 
  // Otherwise put the current item push Into the temporary array 
  if (n.indexOf(this[i]) == -1) n.push(this[i]);
 }
 return n;
};
Array.prototype.unique2 = function()
{
  var n = {},r=[]; //n for hash Table, r Is a temporary array 
  for(var i = 0; i < this.length; i++) // Traverses the current array 
  {
    if (!n[this[i]]) // if hash There is no current item in the table 
    {
      n[this[i]] = true; // deposit hash table 
      r.push(this[i]); // Take the current item of the current array push Into the temporary array 
    }
  }
  return r;
};
Array.prototype.unique3 = function()
{
  var n = [this[0]]; // The result array 
  for(var i = 1; i < this.length; i++) // From the first 2 The item begins to traverse 
  {
    // If the current array is the first i The item is first in the current array 1 The next position is not i . 
    // So that means the first i The terms are repeating, ignore them. Otherwise, put it into the result array 
    if (this.indexOf(this[i]) == i) n.push(this[i]);
  }
  return n;
};
Array.prototype.unique4 = function()
{
  this.sort();
  var re=[this[0]];
  for(var i = 1; i < this.length; i++)
  {
    if( this[i] !== re[re.length-1])
    {
      re.push(this[i]);
    }
  }
  return re;
};
var arr = [1,2,2,2,3,3,4,5];
console.log(arr.unique1()); // [1, 2, 3, 4, 5]
console.log(arr.unique2()); // [1, 2, 3, 4, 5]
console.log(arr.unique3()); // [1, 2, 3, 4, 5]
console.log(arr.unique4()); // [1, 2, 3, 4, 5]

Both the first and third methods use the indexOf method of arrays. The purpose of this method is to find the first occurrence of the stored parameter in the array. Obviously, the js engine implements this method by iterating through the groups until it finds the target. So this function is going to waste a lot of time. The second method USES the hash table. Put the existing ones into an object in the form of subscripts. Subscript references are much faster than searching an array with indexOf.

The fourth way is to sort the array and then compare two adjacent values. The JS native sort method is used for sorting, and the JS internal engine is probably used for quicksort. The end result is that this method runs on average about three times as long as the second method, but much faster than the first and third methods.

That's all for this article, I hope you enjoy it.


Related articles: