Two common methods and code for de-duplicating javascript Arrays

Source: Internet
Author: User

The first method is more common.
Ideas:
1. Create a new array to store the results
2. In the for loop, an element is extracted from the original array each time, and indexOf is used to find whether the element exists in the new array.
3. If not, it is saved to the result array.
Copy codeThe Code is as follows:
Array. prototype. unique1 = function (){
Var res = [];
For (var I = 0; I <this. length; I ++ ){
If (res. indexOf (this [I]) =-1 ){
Res. push (this [I]);
}
}
Return res;
}
Var arr = [1, 'A', 'A', 'B', 'D', 'E', 'E', 1, 0]
Alert (arr. unique1 ())

On this basis, it can be slightly optimized, but the principle remains unchanged, and the effect is not obvious.
Copy codeThe Code is as follows:
Array. prototype. unique1 = function (){
Var res = [this [0]; // directly store the first element in the original array into the new array.
For (var I = 1; I <this. length; I ++) {// The loop starts from the second element.
If (res. indexOf (this [I]) =-1 ){
Res. push (this [I]);
}
}
Return res;
}
Var arr = [1, 'A', 'A', 'B', 'D', 'E', 'E', 1, 0]
Alert (arr. unique1 ())

The second method is more efficient than the above method.
Ideas:
1. Sort the original array first
2. Check whether the I-th element in the original array is the same as the last element in the result array. Because the elements have been sorted, the repeated elements are in the adjacent positions.
3. If the elements are different, the elements are stored in the result array.
Copy codeThe Code is as follows:
Array. prototype. unique2 = function (){
This. sort (); // sort first
Var res = [this [0];
For (var I = 1; I <this. length; I ++ ){
If (this [I]! = Res [res. length-1]) {
Res. push (this [I]);
}
}
Return res;
}
Var arr = [1, 'A', 'A', 'B', 'D', 'E', 'E', 1, 0]
Alert (arr. unique2 ())

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.