Using JavaScript for Array de-weight-an efficient algorithm

Source: Internet
Author: User

Recently busy, no time to update the blog, and so busy will be finishing an article using Angularjs to build a medium-sized single-page application (SPA) articles, look forward to! Occupy a hole first.

There are many kinds of algorithms for array de-weight, the following is one.

Ideas are as follows:

    1. Defines an empty object, obj;
    2. Loop array arr, determine if Obj[arr[i]] is false, and if so, place the array element in result and set Obj[arr[i]] to true;
    3. Obj[arr[0]] "must be false, because obj is empty, arr[0] will be placed in result, and Obj[arr[0]] is set to true;
    4. In the process of looping, if any element (such as nth Element) and Arr[0] is the same, then Obj[arr[n]] will be the same as obj[arr[0]] (all true), because key is the same, value must be the same.

So we can go to the heavy.

The code is as follows:

1 functionUnique (arr) {2     varobj={};3     varresult=[];4      for(vari=0;i<arr.length;i++){5         if(!Obj[arr[i]]) {6 Result.push (Arr[i]);7obj[arr[i]]=true;8         }9     }Ten     returnresult; One } A varArray = [32,12,4,27,12,9,20,32,12,8,44,18]; -Console.log (unique (array));

----------------------------------------------------------------------------------Gorgeous split-line----------------------- --------------------------------------------------------------

After writing, we found that there is a simpler array de-RE algorithm, using the array filter method, the following is the code:

1 function () {2     return this. Filter (function  (V, I, m) {3         return i <= m.indexof (v ); 4     }); 5 }; 6 var array = [1,2,3,12,3,2,1,2,30]; 7 array.unique ();

Using JavaScript for Array de-weight-an efficient algorithm

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.