Several methods of the array de-weight in JS

Source: Internet
Author: User

Several methods of the array de-weight in JS
1. Iterate through the array, compare each, compare to the same to delete the following
function Unique (arr) {
for (Var i=0;i<arr.length;i++) {
for (Var j=i+1;j<arr.length;j++) {
if (arr = = Arr[j]) {
                                &NBSP ;               Arr.splice (j,1);
                                                j--;
                                      &NBSP;&NBSP;&NBSP,}
                              &NBSP;&NBSP;&NBSP,}
                      & nbsp;   ,}
                          ret Urn Arr.sort ();
               }
       
2. Iterate through the array, compare each one, compare to the same, remove it, and put it in a new array.
function Unique (arr) {
var result=[],isrepeated;
for (Var i=0;i<arr.length;i++) {
Isrepeated=false;
for (Var j=0;j<result.length;j++) {
if (arr = = Result[j]) {
Isresulted=true;
Break
}
}
if (!isrepeated) {
Result.push (arr);
}
}
return result;
}
3. First order, the preceding paragraph and latter comparison, remove the same item
function Unique (arr) {
var temp=[];
This.sort ();
for (Var i=0;i<arr.length;i++) {
if (arr = = Arr[i+1]) {
Continue
}
Temp[temp.length]=arr;
}
return temp;
}
4. Use a Hashtable structure to record existing elements so that the inner loop can be avoided. It happens that the implementation of Hashtable in JavaScript is extremely simple
function Unique (arr) {
var result=[],hash={};
for (var I=0,elem; (elem = arr)! = null;i++) {
if (!hash[elem]) {
Result.push (Elem);
Hash[elem] = true;
}
}
return result;
}

Several methods of the array de-weight in JS

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.