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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
EDIT: This question was answered almost nine years ago when there were not many useful built-in methods in the
Array.prototype.Now, certainly, I would recommend you to use the
filtermethod.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
nullorundefinedvalues: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 typical 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 pass to the
filtermethod, theBooleanconstructor function, or return the same element in the filter criteria function, for example:Or
In both ways, this works because the
filtermethod in the first case, calls theBooleanconstructor as a function, converting the value, and in the second case, thefiltermethod internally turns 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 use the
filtermethod 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: