High efficiency remove duplicates in JS array

Source: Internet
Author: User

Referenced from: http://www.cnblogs.com/sosoft/archive/2013/12/08/3463830.html

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

1functionUnique (arr) {2var result =[], isrepeated;3for (var i = 0, len = arr.length; i < Len; i++) {4 isrepeated =False;5for (var j = 0, len = result.length; J < Len; J + +) {6if (arr[i] = =Result[j]) {true;< Span style= "color: #008080;" > 8 break; 9 }10 }11 if (! isrepeated) {12  Result.push (Arr[i]); 13 }14 }15 return Result;                 

The general idea is to move the elements of the array to another array one by one, checking to see if the element is duplicated in the process of handling it, and throwing it away if any. As you can see from the nested loops, this method is extremely inefficient. We can use a Hashtable structure to record existing elements so that the inner loop can be avoided. Exactly, the implementation of Hashtable in JavaScript is extremely straightforward and is improved as follows:

function Unique (arr) {    var result = [], hash = {};    For (null; i++if (!  Truereturn result;  http://www.cnblogs.com/sosoft/}          

High efficiency remove duplicates in JS array

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.