Javascript: How to clear undefined values from an array

KT. picture KT. · Mar 7, 2012 · Viewed 26.1k times · Source

I'm trying to loop through an array and delete and skip the elements until only one is existing. i've tried splicing but it messes up my loop because the element from arr[1] then becomes arr[0] etc.

Let's say there are 10 people. I'd like to remove person 1 then keep person 2 then remove person 3 and keep person 4. This pattern will go on until only one is left.

any kind of help will do.

Answer

alexoviedo999 picture alexoviedo999 · Dec 15, 2014

Filter the falsy items:

var a=[1,2,"b",0,{},"",NaN,3,undefined,null,5];
var b=a.filter(Boolean); // [1,2,"b",{},3,5]