How to remove duplicate from list

I have such a list from my web service. I want to eliminate duplication of username:

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 }]; 

Is there a function that allows me to remove duplicate values ​​(one of the elements = Plr1)?

+4
source share
3 answers

DEMO: http://jsfiddle.net/abc123/ZgYbB/

NOTE. The last for loop is just to show that the elements have been deleted and what remains in the array.

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); } 
+1
source

You can use 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); 

It will not work in older browsers out of the box. If you look at the link I posted above, there is Polish to make them work.

+3
source

This will do what you want (assuming you are looking for case-insensitive comparison of usernames).

EDIT add demo: 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; } 
+1
source

Source: https://habr.com/ru/post/1478966/


All Articles