4 ways to repeat an array in JavaScript

Source: Internet
Author: User

The first: It is also the most stupid.

Array.prototype.unique1 = function () {
var r = new Array ();
Label:for (var i = 0, n = this.length; i < n; i++) {
for (var x = 0, y = r.length < y; x + +) {
if (r[x] = = This[i]) {
Continue label;
}
}
R[r.length] = this[i];
}
return R;
}
The second kind: This is the same as the heavenly book.

Array.prototype.unique2 = function () {
Return This.sort (). Join (",,"). Replace (/(, |^) ([^,]+) (,, \2) + (, |$)/g, "$1$2$4"). Replace (/,,+/g, ","). Replace (/,$/, "" " ). Split (",");
}
Third: Using the "hasOwnProperty" method of the object

Array.prototype.unique3 = function () {
var temp = {}, len = This.length;
for (Var i=0 i < Len; i++) {
var tmp = this[i];
if (!temp.hasownproperty (TMP)) {
Temp[this[i]] = "My God";
}
}

len = 0;
var temparr=[];
for (var i in temp) {
temparr[len++] = i;
}
return Temparr;
}

The fourth kind: first sort, the preceding paragraph is more than bottom. This method is very simple, but also practical

Array.prototype.unique4 = function () {
var temp = new Array ();
This.sort ();
for (i = 0; i < this.length; i++) {
if (this[i] = = This[i+1]) {
Continue
}
Temp[temp.length]=this[i];
}
return temp;

}


The following is used frequently, and the efficiency is also very good. Kind of like a hash table feeling.

Array.prototype.unique5 = function () {
var res = [], hash = {};
For (var i=0, Elem; (Elem = this[i])!= null; i++) {
if (!hash[elem])
{
Res.push (Elem);
Hash[elem] = true;
}
}
return res;
}

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.