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?
Thanks
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? Thanks
| |||
feedback
|
I use this method, extending the native Array prototype:
Or you can simply push the existing elements into other array:
| |||||||||||||||||
feedback
|
I needed to do this same task and came upon this thread. I ended up using the array "join" to create a string using a "_" separator, then doing a bit of regex to:-
...then using array "split" to make a cleaned-up array:-
...or in 1 line of code:-
...or, extending the Array object :-
| ||||
feedback
|
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:
| |||
feedback
|
If you need to remove ALL empty values ("", null, undefined and 0):
Example:
Return:
| |||||
feedback
|
Pure javascript:
or
| |||||||||||||||
feedback
|
The clean way to do it.
| |||||
feedback
|
What about that:
| |||||
feedback
|
@Alnitak Actually Array.filter works on all browsers if you add some extra code. See below.
This is the code you need to add for IE, but filter and Functional programmingis worth is imo.
| ||||
feedback
|
This works, I tested it in AppJet (you can copy-paste the code on its IDE and press "reload" to see it work, don't need to create an account)
| |||
feedback
|
If you've got Javascript 1.6 or later you can use https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter This page also contains a nice error-checking version of | |||||||
feedback
|
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... ;) | ||||
feedback
|
Try this. Pass it your array and it will return with empty elements removed. *Updated to address the bug pointed out by Jason
| |||||||||||||
feedback
|
You'll have to loop and then splice() | |||
feedback
|
You'll need use some form of iteration to accomplish this. There isn't any built in mechanism in JavaScript to accomplish the task. | |||
feedback
|