Simple ways:
var arr = [1,2,,3,,-3,null,,0,,undefined,4,,4,,5,,6,,,,];
arr.filter(n => n)
// [1, 2, 3, -3, 4, 4, 5, 6]
arr.filter(Number)
// [1, 2, 3, -3, 4, 4, 5, 6]
arr.filter(Boolean)
// [1, 2, 3, -3, 4, 4, 5, 6]
or - (only for single array items of type "text")
['','1','2',3,,'4',,undefined,,,'5'].join('').split('');
// output: ["1","2","3","4","5"]
or - Classic way: simple iteration
var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,],
len = arr.length, i;
for(i = 0; i < len; i++ )
arr[i] && arr.push(arr[i]); // copy non-empty values to the end of the array
arr.splice(0 , len); // cut the array and leave only the non-empty values
arr // [1,2,3,3,[],Object{},5,6]
via jQuery:
var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];
arr = $.grep(arr,function(n){ return n == 0 || n });
arr // [1, 2, 3, 3, 0, 4, 4, 5, 6]
UPDATE - just another fast, cool way (using ES6):
var arr = [1,2,null, undefined,3,,3,,,0,,,4,,4,,5,,6,,,,],
temp = [];
for(let i of arr)
i && temp.push(i); // copy each non-empty value to the 'temp' array
arr = temp;
arr // [1, 2, 3, 3, 4, 4, 5, 6]
Remove empty values
['foo', '',,,'',,null, ' ', 3, true, [], [1], {}, undefined, ()=>{}].filter(String)
// ["foo", null, " ", 3, true, [1], Object {}, undefined, ()=>{}]
Best Answer
Option 1 A: Clearing
innerHTML
.Option 1 B: Clearing
textContent
.textContent
. According to MDN this will be faster thaninnerHTML
as browsers won't invoke their HTML parsers and will instead immediately replace all children of the element with a single#text
node.Option 2 A: Looping to remove every
lastChild
:firstChild
, but this is updated to uselastChild
as in computer-science, in general, it's significantly faster to remove the last element of a collection than it is to remove the first element (depending on how the collection is implemented).firstChild
just in case it's faster to check forfirstChild
thanlastChild
(e.g. if the element list is implemented as a directed linked-list by the UA).Option 2 B: Looping to remove every
lastElementChild
:Element
(namely#text
nodes and<!-- comments -->
) children of the parent (but not their descendants) - and this may be desirable in your application (e.g. some templating systems that use inline HTML comments to store template instructions).lastElementChild
in IE9.Bonus:
Element.clearChildren
monkey-patch:Element
prototype in JavaScript to simplify invoking it to justel.clearChildren()
(whereel
is any HTML element object).