剔除数组中重复对象
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;
}
作者:阿良
出处:http://www.cnblogs.com/arliang
本文采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议
进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。

浙公网安备 33010602011771号