Bill Brown bio photo

Bill Brown

A complicated man.

Twitter Github

I wanted to remove an item from a Javascript array and looked in vain for a remove function. I did find an implementation of remove using the Array.prototype but I just needed a function to get rid of items that matched a specific criterion.

That's when the trouble started. The splice function—calling its array.splice(index, count) variant—will indeed remove an item or items from the array (and return an array of the items removed for some reason) but it also closes the void left by the removed item and resizes the array all in one fell swoop. So code like this doesn't work as you'd think:

for (var i = 0; i < array.length; i++)
{
   if (array[i].someParameter == "someValue")
   {
      array.splice(i, 1);
   }
}

Since array.length changes with each removal, this code will end up missing some items because it will end too quickly. In the interest of saving future Googling, frustrated Javascripters, here's how I solved the issue:

for (var i = array.length - 1; i >= 0; i--)
{
   if (array[i].someParameter == "someValue")
   {
      array.splice(i, 1);
   }
}

By starting the loop from the top of the array and working backwards, item removals and the dynamic resizing have no effect. If anyone has a better way, I'm all ears. Well, eyes.