How do I remove empty elements from an array in JavaScript?
Is there a straightforward way, or do I need to loop through it and remove them manually?
How do I remove empty elements from an array in JavaScript?
Is there a straightforward way, or do I need to loop through it and remove them manually?
If you need to remove ALL empty values ("", null, undefined and 0):
To remove empty values and Line breaks:
Example:
Return:
UPDATE (based on Alnitak's comment)
In some situations you may want to keep "0" in the array and remove anything else (null, undefined and ""), this is one way:
Return:
For removing holes, you should use
For removing hole, and, falsy (null, undefined, 0, -0, NaN, "", false, document.all) values:
For removing hole, null, and, undefined:
If using a library is an option I know underscore.js has a function called compact() http://documentcloud.github.com/underscore/ it also has several other useful functions related to arrays and collections.
Here is an excerpt from their documentation:
You may find it easier to loop over your array and build a new array out of the items you want to keep from the array than by trying to loop and splice as has been suggested, since modifying the length of the array while it is being looped over can introduce problems.
You could do something like this:
Actually here is a more generic solution:
You get the idea - you could then have other types of filter functions. Probably more than you need, but I was feeling generous... ;)
Another way to do it is to take advantage of the length property of the array : pack the non-null items on the 'left' of the array, then reduce the length. It is an in-place algorithm -does not allocates memory, too bad for the garbage collector-, and it has very good best/average/worst case behaviour.
This solution, compared to others here, is between 2 to 50 times faster on Chrome, and 5 to 50 times faster on Firefox, as you might see here : http://jsperf.com/remove-null-items-from-array
The code below adds the non-enumerable 'removeNull' method to the Array, which returns 'this' for daisy-chaining :
The best way to remove empty elements, is to use
Array.prototype.filter()
, as already mentioned in other answers.Unfortunately,
Array.prototype.filter()
is not supported by IE<9. If you still need to support IE8 or an even older version of IE, you could use the following polyfill to add support forArray.prototype.filter()
in these browsers :