[Discussion] js deduplication of array values

Source: Internet
Author: User

Code

<Script type = "text/javascript">
Array. prototype. distinct = function (){
Var $ = this;
Var o1 = {}; // store the deduplication Value
Var o2 ={}; // store duplicate values
Var o3 = []; // store duplicate values

Var o; // a single variable in the array
For (var I = 0; o = $ [I]; I ++ ){
If (o in o1 ){
If (! (O in o2) o2 [o] = o;
Delete $ [I];
} Else {
O1 [o] = o;
}
}

$. Length = 0; // clear the original array

For (o in o1 ){
$. Push (o );
}


For (o in o2 ){
O3.push (o );
}

Return o3;
}
Var a = [2, 2, 3, 3, 4, 5, 6, 7];
Alert ("original array:" + );
Alert ("repeated elements:" + A. distinct (); //,
Alert ("the sorted array is:" + a); // 5.6, 4, 6
Alert ("the length after sorting is:" + A. Length) // 6
</SCRIPT>

 

A peer is puzzled by the above program code, mainly because he does not understand the following code:

For (var I = 0; o = $ [I]; I ++ ){
If (o in o1 ){
If (! (O in o2) o2 [o] = o;
Delete $ [I];
} Else {
O1 [o] = o;
}
}

 

Finally, we will discuss it as follows:

 

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.