惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
GbyAI
GbyAI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
阮一峰的网络日志
阮一峰的网络日志
Last Week in AI
Last Week in AI
V
Visual Studio Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
The Cloudflare Blog
博客园 - 【当耐特】
博客园 - 叶小钗
量子位
博客园 - 聂微东
S
SegmentFault 最新的问题
美团技术团队
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
宝玉的分享
宝玉的分享
小众软件
小众软件
罗磊的独立博客
有赞技术团队
有赞技术团队
Stack Overflow Blog
Stack Overflow Blog

博客园 - 浙林龙哥

S3 put object upload file,被AI欺骗的一天 How to get blob data using javascript XmlHttpRequest by sync 咖啡之约--体验 SourceAnywhere 安装node.js / npm / express / KMC 选择沃阁橱柜 ASP.NET 4.0的ClientIDMode=”Static”未必是最好 VS 2010 和 .NET 4.0 系列之《ASP.NET 4 Web Forms 的整洁HTML标识 — 客户端ID》篇 .NET 3.5 Ruby学习1-字符串 ImageMagick 详细安装使用 linux (jmagick) Windows XP 上安装 Bind9 BIND9配置 [javascript] 数组去重问题 数组A和B找交集 淘宝图片空间---设计师可免费申请短链接啦! php框架 How to use iBatis/NHibernate in medium trust/partial trust environments like Mosso JVM调优 常用的eclipse plugins
[javascript]数组去重
浙林龙哥 · 2011-03-08 · via 博客园 - 浙林龙哥

数组中去除重复元素的算法:

第一种:常用方式。

Array.prototype.unique = function () {
	var r = new Array();
	label:for(var i = 0, n = this.length; i < n; i++) {
		for(var x = 0, y = r.length; x < y; x++) {
			if(r[x] == this[i]) {
				continue label;
			}
		}
		r[r.length] = this[i];
	}
	return r;
}

第二种:一行代码正则方式。

Array.prototype.unique = function () {
	return this.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",");
}

第三种:利用javascript语言特性。

Array.prototype.unique = function() {
	var temp = {}, len = this.length;
	for(var i=0; i < len; i++)  {
		var tmp = this[i];
		if(!temp.hasOwnProperty(tmp)) {
			temp[this[i]] = "hoho";
		}
	}
	this.length = 0;
	len = 0;
	for(var i in temp) {
		this[len++] = i;
	}
	return this;
}

第四种:循环一遍方式。

Array.prototype.unique = 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;
 
}