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 using Object
instead of String
, Boolean
, or Number
as suggested above.
Specifically, ES5's filter()
already doesn't trigger for undefined
elements within the array; so a function that universally returns true
, which returns all elements filter()
hits, will necessarily only return non-undefined
elements:
> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(function(){return true})
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]
However, writing out ...(function(){return true;})
is longer than writing ...(Object)
; and the return-value of the Object
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 for function(){return true}
.
> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(Object)
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]