Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array Splice without changing the index

I am working on a chat and using an array to hold the users. Here is my problem:

User1 joins and is given Index 0 in the array via push. User2 joins and is given Index 1 in the array via push.

User1 disconnects and is removed via splice.

NOW User2 becomes Index 0.

User1 reconnects and is given Index 1 via push.

User2 disconnects, and Index 1 is removed which is now User1.

This is of course causing a problem.

So my question is how can I remove the item from the array without the index of the other elements changing? Am I on the wrong track here?

like image 538
Cyrus Avatar asked Jun 30 '13 05:06

Cyrus


People also ask

How do you splice an array without indexing?

apply(context, argsArray) calls function in the given context, passing argsArray as the arguments for function. In this case, function is []. splice , which takes the following parameters, in this this order: index - at which to start changing the array.

Does splice mutate the original array?

The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object. 2. The splice() method changes the original array and slice() method doesn't change the original array.

How can we copy array without mutating?

To sort an array, without mutating the original array:Call the slice() method on the array to get a copy. Call the sort() method on the copied array. The sort method will sort the copied array, without mutating the original.


1 Answers

Instead of removing the items from the array with splice(), why not just set the value to null or undefined?

Then when you're adding a new user, you can just scan through the array to find the first available slot.

javascript arrays are simply lists of items - they're not keyed to a specific key like you might be familiar with in PHP. So if you want to keep the same position in the array, you can't remove other items - you need to keep them, and just mark them as empty.


You might scan through something like this:

var users = [];
function addUser(user) {
    var id = users.indexOf(null);
    if (id > -1) {
        // found an empty slot - use that
        users[id] = user;
        return id;
    } else {
        // no empty slots found, add to the end and return the index
        users.push(user);
        return users.length - 1;
    }
}
function removeUser(id) {
    users[id] = null;
}
like image 142
jcsanyi Avatar answered Oct 29 '22 00:10

jcsanyi