剔除数组中重复对象

 

var arr = [
	{id:1},
	{id:2},
	{id:1}
];
/*
unique(arr, 'id'); //->
[{id: 1}, {id: 2}];
unique([1,2,2,2,3,3,4]); //->
[1,2,3,4];
unique(arr, function(item){
	return item.id;
}); //->
[{id: 1}, {id: 2}];
*/
function unique(array, filter){
	var tmpObject = {hasStored: {}, uniqueArray: []}, i, fun;
	if(! filter){ // 没有传filter,使用array的值当作filter
		fun = function(item){
			return item;
		}
	}else{
		if(typeof filter ==='string'){ // 用filter当作key
			fun = function(item){
				return item[filter];
			}
		} else if(typeof filter !== 'function'){ // 出错
			throw {
				message: "The second argument's type must be function/string"
			}
		}
		// 其它,自定义filter
	}
	for(i = 0; i < array.length; i++){
		// 传进三个参数[当前元素,当前下标,数组本身]
		var uniqueKey = fun(array[i], i, array);
		if(! tmpObject['hasStored'][uniqueKey]){
			tmpObject['hasStored'][uniqueKey] = true;
			tmpObject['uniqueArray'].push(array[i]);
		}
	}
	return tmpObject.uniqueArray;
}

  

posted @ 2013-03-15 10:23  Arliang  阅读(315)  评论(0编辑  收藏  举报