&&&& Array de-weight method summary &&&&&

Source: Internet
Author: User

"Array de-weight" This article summarizes 5 ways:

Method One: The Sort method var ary = [1, 4, 2, 3, 1, 2, 2, 3, 3, 2, 5, 2, 1, 2];
Array.prototype.rmSame = function () {
var ary = This.sort (function (A, b) {
Return A-B
});
for (var i = 0; i < ary.length; i++) {
if (ary[i] = = = Ary[i + 1]) {
Ary.splice (i, 1);
i--;
}
}
return ary;
};
Console.log (Ary.rmsame ());
Method two, double-loop comparison
var ary1 = [1, 4, 2, 3, 1, 2, 2, 3, 3, 2, 5, 2, 1, 2];
Array.prototype.rMsame = function () {
for (Var i=0;i<this.length;i++) {
var olis=this[i];
for (Var j=i+1;j<this.length;j++) {
if (Olis===this[j]) {
This.splice (j,1);
j--;
}
}
}
return this;
};console.log (Ary1.rmsame ()); //Method Three: Key value pairvar ary = [1, 2, 1, 2, 1, 2, 1, 4, 5, 63, 2, 5, 432, 24]; Array.prototype.rmSome = function () {
var obj={};
for (Var i=0;i<this.length;i++) {
var cur=this[i];
if (obj[cur]==cur) {
THIS[I]=THIS[THIS.LENGTH-1];
this.length--;
i--;
Continue
}
Obj[cur]=cur;
}
return this;
};console.log (Ary.rmsome ());//method four new array var ary1=[];
for (var i=0; i<ary.length; i++) {
/!*if (Ary1.indexof (Ary[i]) ==-1) {
Ary1.push (Ary[i]);
}else{
Ary.splice (i,1);
i--;
}*!/
if (Ary1.indexof (Ary[i]) ==-1) {
Ary1.push (Ary[i]);
}}//method Five can record an array of objects to heavy var obj={};
for (var i=0; i<ary.length; i++) {
var cur=ary[i];
if (Obj[cur]) {
obj[cur]++;
}else{
Obj[cur]=1;
}
}
var ary=[];
for (var attr in obj) {
Ary.push (attr);
}

&&&& Array de-weight method summary &&&&&

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.