Remove undefined and empty elements from a javascript array.

Yesterday afternoon, Nick presented Jon and I with a dilemma. There was a hint of trouble removing undefined object references from an array.

While they came up with their own solution, I knocked out a flexible solution that I hope someday will serve some wayward individual that runs into this same problem.

Rather than use array.splice() to remove the naughty bits from the array in question, I rather identified the acceptable items, and jammed them in to a new array. In doing so, we remove blank string elements, undefined references, NULLs and FALSEs.

Anyways, here’s the code for my solution (assuming arr is rife with the evils described above):

So yea, using a lesser-known JS looping technique, we can iterate through the array, let JavaScript determine the status of the element, and then stack it on our new array (if it passes the test). When it’s all finished, we can toss out the remains (arr).

If you enjoyed this post, then tweet about it!

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.