问题
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?
回答1:
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
回答2:
The best way using lodash is _.without
Example:
const newArray = _.without([1,2,3,undefined,0,null], undefined);
回答3:
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);
回答4:
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);
回答5:
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 ]
回答6:
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);
回答7:
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 );
回答8:
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);
回答9:
With ES6 Array#filter method
array.filter(item => item !== undefined)
回答10:
const finalArray = initialArray.filter(i => Boolean(i))
来源:https://stackoverflow.com/questions/39519440/how-to-remove-undefined-values-from-array-but-keep-0-and-null