Alex Rivera | Logout

Remove empty elements from an array in Javascript

Asked 2008-11-11T15:48:54.113
1666

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?

Edit
Report

2 Answers

60

The clean way to do it.

var arr = [0,1,2,"Thomas","false",false,true,null,3,4,undefined,5,"end"];
arr = arr.filter(Boolean);
// [1, 2, "Thomas", "false", true, 3, 4, 5, "end"]
answered 2011-03-26T16:57:34.957
22

With Underscore/Lodash:

General use case:

_.without(array, emptyVal, otherEmptyVal);
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);

With empties:

_.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');
--> ["foo", "bar", "baz", "foobar"]

See lodash documentation for without.

answered 2012-11-30T18:25:11.080

Your Answer