0

I am trying to manage the position/order of each user logged in my app. I made an array that is updated every time that someone enters. until now, it's working fine.

[...]
var row_of_users=[];//my array of users.
var visits=0;//just a count of users logged in.

io.on('connection', function(socket){
var user=socket.id;
visits++;
row_of_users.push(user);
console.log(row_of_users);
[...]

in the console.log shows:

[ 'BnUtfcyNniEWNwN3AAAA', 'IkE3l4oMBXt5dEsOAAAB', 't5gzbSru7oDR44T7AAAC', 'yB2X4G55YqcvDgHcAAAD' ]

but when an user leaves, socket.io ignores the user.id and deletes the last object in the array.

socket.on('disconnect', function(){
visits--;
row_of_users.pop(user);
});

if i close THE FIRST user tab in my browser (**BnUtfcyNniEWNwN3AAAA) in the console.log now shows this:**

[ 'BnUtfcyNniEWNwN3AAAA', 'IkE3l4oMBXt5dEsOAAAB', 't5gzbSru7oDR44T7AAAC' ]

like if the last user disconnected.

What's happening here? and how can i update the array correctly? I didn't post the entire code cuz my language is portuguese and the variables are in portuguese too.

Daniel Vettorazi
  • 112
  • 1
  • 1
  • 7

2 Answers2

1

array.pop() doesn't take any arguments and will always pop the last element.

From MDN:

The pop() method removes the last element from an array and returns that element.

To remove the Nth element use:

array.splice(N, 1)

Or in your case:

row_of_users.splice(row_of_users.indexOf(user), 1)

Spooze
  • 378
  • 1
  • 10
0

Your answer lies here: How do I remove a particular element from an array in JavaScript?

Basically, you'll use indexOf(socket.id) and splice that index from the row_of_users array.

unm4sk
  • 335
  • 1
  • 8