Flex Tip: Remove/delete item from an array

Updated March 10th, 2009
It turns out this is probably not the best way to do it. As per the comments below, be careful using the delete command as it will only set the element to undefined (the length of the array won’t be shortened. I considered deleting this post, but I think it may still be useful in that it helps clarify the difference between slice and delete.

Original post starts here…

If you search for this topic you’ll find that this can be accomplished using the splice function.

MyArray.splice(3, 1);

This was how I was doing it for a while, but I just recently discovered a simpler method.

delete MyArray[3]

Hope this helps,
Hillel

10 thoughts on “Flex Tip: Remove/delete item from an array”

  1. From livedocs:
    “The delete operator sets the value of an array element to undefined, but it does not remove the element from the array.”
    So splice is the way.

    1. Peter,

      Thanks, you’re absolutely right. I didn’t discover that fact until after I had written the post. I’ve added an update to the post to reflect this additional piece of info.

      Best,
      Hilllel

  2. It’s still useful in fact, when you do simply need to set the value to undefined. Then using operations like for example .join() will ignore the value.

    Also, this works much better than splice() if you’re altering the array in a for each loop. If you splice() in a for each, you have to be careful with the positioning of the elements. Not so with delete, because the indexes remain intact.

    Of course this still applies only if you can live with the indices being off.

    1. Crystal,

      Strange timing…. I actually just made the mistake of using the wrong one in my code. It took me quite a while to spot the bug.

      Best,
      Hillel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s