JS cleverly removes repeated items in the array

Source: Internet
Author: User
Tags hasownproperty

Looking at the source code of Yui from time to time, there will always be some gains.

I. source code in Yui'CopyCodeThe Code is as follows: var toobject = function (){
VaR o = {};
For (VAR I = 0, j =. length; I <j; I = I + 1) {// I have adjusted it here. The Yui source code is I <. length
O [A [I] = true;
}
Return O;
};
VaR keys = function (o ){
VaR A = [], I;
For (I in O ){
If (O. hasownproperty (I) {// here, the Yui source code is Lang. hasownproperty (O, I)
A. Push (I );
}
}
Return;
};
VaR uniq = function (){
Return keys (toobject ());
};

Note: For ease of writing, I omit the class names before each method. You can check the Yui source code on your own. Both 2.7.0b and 2.8.0r4 can be used (the code in this part is the same ).

Ii. Ideas of this method
1. first, an object is generated with the value of the target array as the key. this step is the core: Because keys in an object cannot be repeated, so that repeated values are cleverly excluded;

2. traverse the generated objects and put these keys in an array. OK. This is done! (Easy, just two steps)

Iii. Features of this method
1. this method only traverses twice regardless of the number of items in the array, which has obvious performance advantages (think about your previous practice: Compare array items one by one, the performance is poor, you can imagine ).

2. in my tests, this method is only applicable to the one-dimensional array of strings and numbers (I think it is too easy to exclude repeated items for multi-dimensional arrays !).

For other methods, refer to the previous article.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.