Javascript Splice Ain't Remove

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.

About this Entry

This page contains a single entry by bbrown published on December 27, 2007 6:00 AM.

Review of High School Musical was the previous entry in this blog.

Resolution Recap is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Feedback to