Javascript Array Splice without changing the index

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

Another option is to use a javascript object instead of an array.

Something like this:

var users = {};

users[1] = 'user 1';
users[2] = 'user 2';

delete users[1];
alert(users[2]);        // alerts "user 2"
alert(typeof users[1]); // alerts "undefined"

You lose the array length property though, so you'll have to keep track of your max user number yourself.


Use delete instead of splice.

> a = ['1', '2', '3']
< Array [ "1", "2", "3" ]

> delete a[1]
< true

> a
< Array [ "1", undefined × 1, "3" ]

> a.length
< 3