Recommended two methods for removing duplicated JavaScript Arrays: javascript Array

Source: Internet
Author: User
Tags javascript array

Recommended two methods for removing duplicated JavaScript Arrays: javascript Array

1. array deduplication;

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<arr.length; i++){    if(result.indexOf(arr[i])==-1){      result.push(arr[i])    }  }  console.log(result)}      arr(aa)

Method 2:

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 there are duplicates of the elements. If so, the elements 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 two methods of de-duplicating the JavaScript array are all the content shared by the editor. I hope to give you a reference, and I hope you can provide more support for the customer's house.

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.