In certain situations, it may happen that we have undefined
or generally falsy values in Array structures. For instance when reading and filling data f
var data = Object.keys(data)
This will remove undefined values but array index will change
var arr1 = [NaN, 0, 15, false, -22, '',undefined, 47, null];
var array1 = arr1.filter(function(e){ return e;});
document.write(array1);
single lined answer
data.filter(Boolean)
Is the most short and readable way to do it.
As Diogo Capela said, but where 0 is not filtered out as well.
[].filter(item => item !== undefined && item !== null)
If you have an array of objects and want to remove all null
and undefined
items:
[].filter(item => !!item);
Inline using lambda
result.filter(item => item);