JavaScript methods for removing array duplicates based on objects _javascript tips

Source: Internet
Author: User

The examples in this article describe the way JavaScript removes array duplicates based on objects. Share to everyone for your reference, specific as follows:

In JavaScript, removing an array of duplicates is a very common function and is often asked in interviews. Many people in the face of this problem, the general is to use a multi-level for loop to step by step comparison, and then delete, so not only the amount of code, And the performance is also very bad. In JavaScript objects, one feature is that the key never repeats, and if it repeats, it overwrites the front.

Three steps:

To convert an array to a JS object
2# the value of the array into the key in the JS object
3# restores an object to a group

var toobject = function (arr) {
    var obj = new Object ();//Private Object
    var j = arr.length;
    for (Var i=0 i < J; +i+) {
        Obj[arr[i]] = true;
    }
    return obj;
}
var keys = function (obj) {
    var arr = [];
    for (var attr in obj) {
        if (Obj.hasownperpoty (attr)) {
            arr.push (attr);
        }
    }
    return arr;
}
var uniq = function (arr) {//Remove duplicates return
    keys (Toobject (Newarr));
}

In use, the array passed to the Uniq function can be, this method uses JavaScript object features, very efficient and concise, but also the bottom of the Yahoo Yui implementation.

More readers interested in JavaScript-related content can view the site topics: "javascript array Operation tips Summary", "JavaScript traversal algorithm and Skills summary", "JavaScript Mathematical calculation Usage Summary", " JavaScript data structure and algorithm skills summary, "JavaScript switching effects and techniques summary", "JavaScript Search Algorithm Skills Summary", "JavaScript animation effects and techniques summary" and "JavaScript error and debugging skills Summary"

I hope this article will help you with JavaScript programming.

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.