How to remove undefined values from array but keep 0 and null
You can use _.compact(array);
Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are falsey.
See: https://lodash.com/docs/4.15.0#compact
The best way using lodash is _.without
Example:
const newArray = _.without([1,2,3,undefined,0,null], undefined);
No need for libraries with modern browsers. filter is built in.
var arr = [ 1, 2, 3, undefined, 0, null ];
var updated = arr.filter(function(val){ return val!==undefined; });
console.log(updated);
With lodash, you can do simply:
var filtered = _.reject(array, _.isUndefined);
If you also want to filter null
as well as undefined
at some point:
var filtered = _.reject(array, _.isNil);