Duplicate values are being storing into an array of object
Based on the given userID
need to out the duplicate userId
,
if it exist do nothing, else push that userId
into the teamSocketsList array
But with the below piece of code duplicate values are being stored into an array teamSocketsList
var TeamUser = {
userId : userID,
socketId : socket.id
}
var i = $.inArray( userID, teamSocketsList );
if(i == -1){
teamSocketsList.push(TeamUser);
}else{
teamSocketsList = jQuery.grep(teamSocketsList, function(value) {
return value != userID;
});
}
Actual Result:
[
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]
Expected Result:
[
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
]
Edit:
Here I'm expecting userID
to be pushed in to an array teamSocketsList
based on the condition, if at all the given userID
matches in the present list should return false or do nothing. Otherwise, (iff, it's not at all included then) store it into an array with the auto-generated socketId
value
The logic which I had tried to implement was to check whether if that array is empty or not and then, traverse all the elements in the array list so that whenever userID
were given as an input it must check the condition and then push that element.
Based on the present answers put up, it'll store the duplicate values and then sort it on and assign it back to teamSocketsList
, that's fine.