我的网络服务中有这种列表。我想消除用户名重复:
Mylist = [{
"username": "Plr1",
"is_online": true,
"email": null,
"message": null,
"direction": 1,
"image_url": ""
}, {
"username": "plr2",
"is_online": false,
"email": "",
"message": null,
"direction": 1,
"image_url": ""
}, {
"username": "plr1",
"is_online": false,
"email": "",
"message": null,
"direction": 1,
"image_url": null
}];
是否有一个允许我删除重复值的函数(元素之一= Plr1)?
答案 0 :(得分:3)
您可以使用Array.filter
var Mylist = [{"username":"Plr1","is_online":true,"email":null,"message":null,"direction":1,"image_url":""},{"username":"plr2","is_online":false,"email":"","message":null,"direction":1,"image_url":""},{"username":"plr1","is_online":false,"email":"","message":null,"direction":1,"image_url":null} ];
var keys = [];
var newList = Mylist.filter(
function(x){
var val = x.username.toLowerCase();
if (!keys[val]) {
keys[val] = true;
return true;
}
return false;
}
);
keys = null;
console.log(newList);
它不适用于旧版浏览器。如果你看一下我上面发布的链接,就会有一个pollyfill让它们起作用。
答案 1 :(得分:1)
这将做你想要的(假设你正在寻找用户名的不区分大小写的比较)。
编辑以添加演示:http://jsfiddle.net/vBZhR/
var Mylist= [{"username":"Plr1","is_online":true,"email":null,"message":null,"direction":1,"image_url":""},{"username":"plr2","is_online":false,"email":"","message":null,"direction":1,"image_url":""},{"username":"plr1","is_online":false,"email":"","message":null,"direction":1,"image_url":null} ];
dedupe(Mylist);
function dedupe(list) {
var usernames = {};
for (var i in list) {
if (usernames[list[i].username.toLowerCase()]) {
list.splice(i, 1);
} else {
usernames[list[i].username.toLowerCase()] = true;
}
}
return list;
}
答案 2 :(得分:1)
DEMO:http://jsfiddle.net/abc123/ZgYbB/
注意:最后一个for循环只是为了显示项目已被移除以及数组中剩下的内容。
JS:
var Mylist= [{"username":"Plr1","is_online":true,"email":null,"message":null,"direction":1,"image_url":""},{"username":"plr2","is_online":false,"email":"","message":null,"direction":1,"image_url":""},{"username":"plr1","is_online":false,"email":"","message":null,"direction":1,"image_url":null} ];
for (var i = 0; i < Mylist.length; i++) {
for(var j = i + 1; j < Mylist.length; j++) {
if(Mylist[i].username.toLowerCase() == Mylist[j].username.toLowerCase())
Mylist.splice(j, 1);
}
}
//Not needed just proof that items were removed.
for (var i = 0; i < Mylist.length; i++) {
alert(Mylist[i].username);
}