Two Methods for deleting repeated array values (deduplication) using JavaScript

Source: Internet
Author: User
Tags javascript array
The criptarray type does not provide the de-duplicated value method. We need to write a function to delete the array's repeated value. This article introduces the two JavaScript methods used by coders to delete the array's repeated values (de-duplicated) for more information, see. Javascript array deduplication Method 1:

The Array type does not provide the deduplication method. If you want to remove the repeated elements of the Array, you have to find a solution:

Method 1: Use the indexOf method;

var aa=[1,3,5,4,3,3,1,4]function arr(arr) {  var result=[]  for(var i=0; i

Method 2 of removing the javascript array:

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

Method 2: The general idea is to move the array elements one by one to another. During the handling process, check whether the elements are repeated. If yes, they are discarded directly. From nested loops, we can see that this method is very inefficient. We can use a hashtable structure to record existing elements, so as to avoid inner loops. Exactly, implementing hashtable in Javascript is extremely simple, and the improvements are as follows:

function unique(arr) { var result = [], hash = {}; for (var i = 0, elem; (elem = arr[i]) != null; i++) { if (!hash[elem]) { result.push(elem); hash[elem] = true; } } return result;}

The above is all the content of the article, hoping to help the coders.

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.