How do I eliminate repeating elements in an array? (Interview topics)

Source: Internet
Author: User

The first time you see this topic, the idea is to find the duplicate elements in the array, and then delete them. The following is a specific code implementation:

var data = [' Blue ', ' red ', ' green ', ' Blue ']; function Uniquedata (data) {    = data.sort ();      for (var i = 0; i < data.length; i++) {        if (data[i] = = = Data[i + 1]            ) {1< c14>);        }    }     return data;} Uniquedata (data);

The above method is relatively simple, but the disadvantage is that after using the sort () method, the original array is changed, the following is the optimized code:

var data = [' Blue ', ' red ', ' green ', ' Blue ']; function  Uniquedata (data) {    for (var i = 0; i < data.length; i++) {        for (J  = i + 1; J < Data.length; J+ +            ) {if (data[i] = = = Data[j]) {                1);     }}} return data;} Uniquedata (data);

Above this method, iterate over the elements in the array, compare any of the two are equal, if you want to wait, the next one from the array to remove, but if the array of elements, this method does not seem so good.

Here is another way of thinking about creating a new array, adding elements from the original array to the new array (judging whether the new array already contains elements from the original array, and if not, adding the elements from the original array to the new array, if they already exist, without adding them), so you can avoid repeating the elements. Take a look at the following code:

var data = [' Blue ', ' red ', ' green ', ' Blue ']; function NewData (data) {    varnew  Array ();      for (var i = 0; i < data.length; i++) {        if (Ndata.indexof (data[i]) = =-1) {
    
     ndata.push (Data[i]);        }    }    
     return Ndata;} NewData (data);

How do I eliminate repeating elements in an array? (Interview topics)

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.