js去除数组的重复元素和去除数组中相邻的重复元素

 //去除数组的重复元素
Array.prototype.distinct = function(){
	var $ = this;
	var o1 = {};
	var o2 = {};
	var o3 = [];
	var o;
	for(var i=0;o = $[i];i++){
		if(o in o1){
			if(!(o in o2)) o2[o] = o;
			delete $[i];
		}else{
			o1[o] = o;
		}
	}
	$.length = 0;
	for(o in o1){
		$.push(o);
	}
	
	for(o in o2){
		o3.push(o);
	}
		
	return o3;
}


var obj = {};
var o1 = obj, o2 = obj , o3 = {};  //假设变量o1,o2指向同一对象obj, o3为一新对象;
var a = [2,3,3,4,4,4,4,5,6,'a','a','a','b','a','b','c',o1,o2,o3];
alert("原数组:" + a);
alert("有重复的元素是:" + a.distinct());
alert("整理后的数组是:" + a);
alert("整理后的长度是:" + a.length)

 

  

 

// 去除数组中相邻的重复元素
Array.prototype.distinctCloseTo = function() {
	var $ = this;
	var o3 = new Array();
	var t = 0
	for (var i = 0; i < $.length; i++) {
		if ($[i] != $[i - 1]) {

			o3[t] = $[i];
			t++;
		}
	}
	$.length = 0;
	for (var j = 0; j < o3.length; j++) {
		$[j] = o3[j];
	}
	return o3;
}
var obj = {};
var o1 = obj, o2 = obj, o3 = {}; // 假设变量o1,o2指向同一对象obj, o3为一新对象;
var a = [2, 3, 3, 4, 4, 4, 4, 5, 6, 'a', 'a', 'a', 'b', 'a', 'b', 'c', o1, o2,o3];
alert("原数组:" + a);
alert("整理后的数组是:" + a.distinctCloseTo());
alert("整理后的长度是:" + a.length)
 

你可能感兴趣的:(前端)