JS数组去重


<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<script>
			Array.prototype.unique3 = function(){
				var res = [];
				var json = {};
				for(var i = 0; i < this.length; i++){
					var objKey = JSON.stringify(this[i]);//把数组值序列化,不然会出bug
					if(!json[objKey]){
				   		res.push(this[i]);
				   		json[objKey] = 1;
				  	}
				}
				console.log(json);
				return res;
			}
			
			var arr = [{id:1},{name:'das'},{id:2},{name:0},{id:2},"dsda",{name:'das'}];
			console.log(arr.unique3());
			
			var arrNew = [
				{
					id:1,
					name:'aa'
				},
				{
					id:1,
					name:'aa',
				},
				{
					id:2,
					name:'bb'
				},
				{
					id:2,
					name:{
						n:"1"
					}
				},
				{
					id:2,
					name:{
						n:"1"
					}
				},
				{
					id:2,
					name:{
						n:"2"
					}
				},
				{
					id:1,
					name:'aa'
				},
				{
					id:1
				},
				{
					id:2
				},
				{
					id:2
				},
				1,
				1,
				[1,2],
				[1,2],
				[1,2,]
			]
			console.log(arrNew.unique3());
			
			var arr_1 = [
				{
					id:1,
					name:[1,2]
				},
				{
					id:1,
					name:[1,2]
				},
				{
					id:1,
					name:[1,]
				},
				{
					id:1,
					name:[1]
				},
			]
			console.log(arr_1.unique3());
		</script>
	</body>
</html>

posted @ 2019-01-02 12:10  栖息地  阅读(82)  评论(0编辑  收藏  举报