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?
I'm simply adding my voice to the above “call ES5's
Array..filter()
with a global constructor” golf-hack, but I suggest usingObject
instead ofString
,Boolean
, orNumber
as suggested above.Specifically, ES5's
filter()
already doesn't trigger forundefined
elements within the array; so a function that universally returnstrue
, which returns all elementsfilter()
hits, will necessarily only return non-undefined
elements:However, writing out
...(function(){return true;})
is longer than writing...(Object)
; and the return-value of theObject
constructor will be, under any circumstances, some sort of object. Unlike the primitive-boxing-constructors suggested above, no possible object-value is falsey, and thus in a boolean setting,Object
is a short-hand forfunction(){return true}
.returns
'Misusing' the for ... in (object-member) loop. => Only truthy values appear in the body of the loop.
This one will only remove empty values and not falsey ones, which I think is more desirable.
There is an option to also remove null values.
This method should be much faster than using splice.
If anyone is looking for cleaning the whole Array or Object this might help.
Output:
Removes anything that is
null
,undefined
,""
," "
,empty object
orempty array
jsfiddle here