JS array deduplication

Source: Internet
Author: User
JS array deduplication

JS array deduplication

Javascript
20:31:31 read 345
Comment 0 font size: large, medium, and small subscriptions

Deduplication of the js array removes the repeated elements in the array:

Array. Prototype. delrepeat = function (){
VaR newarray = new array ();
VaR Len = This. length;
For (VAR I = 0; I <Len; I ++ ){
For (var j = I + 1; j <Len; j ++ ){
If (this [I] === this [J]) {
J = ++ I;
}
}
Newarray. Push (this [I]);
}
Return newarray;
} But it is obvious that the for loop is embedded with another for loop. It must be time-consuming for a large amount of data! Inefficient! A new method has been optimized through search and expert guidance:

Array. Prototype. delrepeat = function (){
VaR newarray = [];
VaR provisionaltable = {};
For (VAR I = 0, item; (item = This [I])! = NULL; I ++ ){
If (! Provisionaltable [item]) {
Newarray. Push (item );
Provisionaltable [item] = true;
}
}
Return newarray;
} Is to use a temporary provisionaltable object and use the value of the array as the key value of the provisionaltable object. If the corresponding value does not exist, push the value of this array to the new array. Efficiency is improved, but there is a bug, That is, assuming that the array is replaced with convertible numbers and strings, such as the array [6, "6"], then it will be removed. Tragedy, while seeking a solution.

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.