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've got Javascript 1.6 or later you can use
Array.filter
using a trivialreturn true
callback function, e.g.:since
.filter
automatically skips missing elements in the original array.The MDN page linked above also contains a nice error-checking version of
filter
that can be used in JavaScript interpreters that don't support the official version.Note that this will not remove
null
entries nor entries with an explicitundefined
value, but the OP specifically requested "missing" entries.With Underscore/Lodash:
General use case:
With empties:
See lodash documentation for without.
Since nobody else mentioned it and most people have underscore included in their project you can also use
_.without(array, *values);
.EDIT: This question was answered almost 9 year ago, when there were not much useful built-in methods in the
Array.prototype
.Now, certainly I would just recommend you to use the
filter
method.Take in mind that this method will return you a new array with the elements that pass the criteria of the callback function you provide to it, for example, if you want to remove
null
orundefined
values:It will depend on what you consider to be "empty", for example if you were dealing with strings, the above function wouldn't remove elements that are an empty string.
One common pattern that I see often used is to remove elements that are falsy, which include an empty string
""
,0
,NaN
,null
,undefined
, andfalse
.You can simply pass to the
filter
method, theBoolean
constructor function, or simply return the same element in the filter criteria function, for example:Or
In both ways this works because the
filter
method in the first case, calls theBoolean
constructor as a function, converting the value, and in the second case, thefilter
method internally converts the return value of the callback implicitly toBoolean
.If you are working with sparse arrays, and you are trying to get rid of the "holes", you can simply use the
filter
method passing a callback that returns true, for example:Old answer: Don't do this!
I use this method, extending the native Array prototype:
Or you can simply push the existing elements into other array:
Simple ES6
You should use filter to get array without empty elements. Example on ES6