Posts Tagged ‘splice’

To splice or not to delete

Friday, August 14th, 2009

I haven’t blogged much about programming recently due to being too busy… too busy to blog, not too busy to program.

This is just a swift post to highlight an important distinction that I haven’t seen mentioned anywhere else, and which recently I realised the siginificance of.

In javascript, what’s the difference between

delete my_array[i];

and

my_array.splice(i, 1);

Superficially they’re the same – they each remove the ith element from an array. But the crucial difference is that delete leaves a gap in the array, so there will no longer be an ith element – the array jumps straight from the (i-1)th to the (i+1)th element. But splice moves the (i+1)th element into the ith place in the array, and so on, shortening the array by one but moving everything along to fill the gap.

Why is this important?

If your code relies often on iterating through an array thus:

for(i=0;i<my_array.length;i++)
{
    //some code
}

then any future iterations over the array will throw errors if you used delete to remove the ith element. But the iterations should still work if you used the splice method.

One note of caution, if you carry out

my_array.splice(i, 1);

within a loop over i, you should add the line

i--;

immediately after, to make sure you don’t miss out the next array element (which is now, of course, not in the (i+1)th place, but in the ith place).