Six ways to summarize JavaScript arrays _javascript tips

Source: Internet
Author: User
Tags javascript array

A question to be prepared at the front end of the interview: How to remove duplicates from JavaScript array. As far as I know, Baidu, Tencent, Shanda and so on in the interview has been out of this topic. The problem seems simple, but it's actually a hidden murder. The test is not only to achieve this function, but also to see your computer program implementation of the in-depth understanding.

I've come up with three algorithms to achieve this:

Array.prototype.unique1 = function ()
{
 var n = [];//A new temporary array for
 (var i = 0; i < this.length; i++)//traverse the current array
 {
 //If Part I of the current array has been saved in a temporary array, skip,
 //Otherwise push the current item to the temporary array if
 (N.indexof (this[i]) = = 1) n.push (This[i]);
 } return
 n;
}
Array.prototype.unique2 = function ()
{
 var n = {},r=[];//n is a hash table, r is a temporary array for
 (var i = 0; i < this.length; i++)//traverse the current array
 {if
 (!n[this[i]])//If there is no current item
 {N[this[i] in the hash table
  = true;//deposit Hash Table
  R.push (this [i]); Push the current item of the current array into the temporary array
 } return
 r;
}
Array.prototype.unique3 = function ()
{
 var n = [this[0]];//result array for
 (var i = 1; i < this.length; i++)// Traversal from the second item
 {
 //If the first occurrence of the current array in the current array is not the position I,
 //Then the item I is duplicated, ignored. Otherwise deposit the result array
 if (This.indexof (this[i]) = = i) N.push (This[i]);
 }
 return n;
}

Both the 1th and 3rd methods use the IndexOf method of the array. The purpose of this method is to find the position where the parameter is stored for the first time in the array. It is obvious that the JS engine will iterate through the array when it implements this method until it finds the target. So this function will waste a lot of time. The 2nd method uses a hash table. To deposit an object in a form that has already appeared through the subscript. The subscript reference is much faster than searching the array with indexof.

To determine the efficiency of these three methods, I did a test program that generated an array of 10000-length random numbers, and then tested the execution time in several ways. The results show that the second method is much faster than the other two methods. But memory footprint should be more than the second method, because there is more than one hash table.  This is called space exchange time. This is the test page, you can also go to see.

According to HPL Daniel, I wrote a fourth way:

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;
}

The idea of this method is to sort the array first and then compare the adjacent two values. The sort time uses the JS native sort method, the JS engine interior should be uses the quick sort. The result of the final test is that this method runs about three times times the average of the second method, but much faster than the first and third methods.

Fifth method

Recently in doing the "search history" function also used, began to use the IndexOf method, the method in ECMA5 only support, for ie8-is not supported.

We can write a function ourselves (the method of the array object is defined on the prototype object), as follows:

Array.prototype.unique = function () {
  var length = this.length;
  if (length <= 1) {return this
    ;
  }
  if (! Array.prototype.indexOf) {    
    Array.prototype.indexOf = function (item) {
      var L = this.length, i = 0, r =-1;
      if (l <= 0) {
return-1;
For
      (; i < L; i++) {
        if (this[i] = = Item) {
          r = i;
        }
      } return r;
    }
  }
  
  var result = []; Go to heavy array for
  (var i = 0; i < length; i++) {
    if (Result.indexof (this[i)) = = 1) {
      Result.push (this[i]);
    } return result
  ;
}

Sixth method

The array type does not provide a way to repeat, if you want to kill the repeating elements of the array, you have to do it yourself:

function Unique (arr) {
  var result = [], isrepeated;
  for (var i = 0, len = arr.length i < len; i++) {
    isrepeated = false;
    for (var j = 0, Len = result.length J < Len; J + +) {
      if (arr[i] = Result[j]) {  
        isrepeated = true;
        break;
      }
    }
    if (!isrepeated) {
      result.push (arr[i]);
    }
  return result;
}

The overall idea is to move the elements of the array to another array, the process of handling to check whether the element is duplicated, if there is a direct throw away. It can be seen from nested loops that this method is extremely inefficient. We can use a Hashtable structure to record existing elements so that the inner loops can be avoided.

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.