In javascript, I want to remove undefined values, but keep the values 0 and null from an array.
[ 1, 2, 3, undefined, 0, null ]
How can I do it cleanly?
You can use _.compact(array);
Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are falsey.
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);
Using lodash, the following remove only undefined values from the array:
var array = [ 1, 2, 3, undefined, 0, null ];
_.filter(array, function(a){ return !_.isUndefined(a) }
--> [ 1, 2, 3, 0, null ]
Or, the following will remove the undefined, 0 and null values:
_.filter(array)
--> [1, 2, 3]
And if you want to remove null and undefined values from the array, but keep the values equal to 0:
_.filter(array, function(a){ return _.isNumber(a) || _.isString(a) }
[ 1, 2, 3, 0 ]
With ES6 Array#filter method
array.filter(item => item !== undefined)
Vanilla JS solution:
By using ===
, you can check if the value is actually undefined
and not falsy
.
Both snippets below will give you an array with [1, 2, 3, 0, null]
.
Both modify the original array.
// one liner - modifies the array in-place
[ 1, 2, 3, undefined, 0, null ].forEach( function(val, i, arr){
if(val===undefined){arr.splice(i,1)}; // remove from the array if actually undefined
});
// broken up for clarity - does the same as the above
var myarray = [ 1, 2, 3, undefined, 0, null ];
myarray.forEach( function(val, i, arr){
if(val===undefined){arr.splice(i,1)};// remove from the array if actually undefined
});
console.log(myarray );
You can use lodash to do this,
you can use _.omitBy(object, _.isUndefined); https://lodash.com/docs/4.17.15#omitBy
in the place of _.isUndefined you can even use _.isNumber, _.isNull and lot of functions.
Go to lodash webside and search "is" in search and you can get the list of functions.
You can try this one.
var array = [ 1, 2, 3, undefined, 0, null ];
var array2 = [];
for(var i=0; i<array.length; i++){
if(!(typeof array[i] == 'undefined')){
array2.push(array[i]);
}
}
console.log(array2);
Filter the given array for elements not equal to undefined.
const initialArray = [ 1, 2, 3, undefined, 0, null ];
const finalArray = initialArray.filter(element => element !== undefined);
const finalArray = initialArray.filter(i => Boolean(i))