如何从数组中删除未定义的值但保持0和null

JLa*_*oie 41 lodash

在javascript中,我想删除未定义的值,但保持数组中的值0和null.

[ 1, 2, 3, undefined, 0, null ]
Run Code Online (Sandbox Code Playgroud)

我怎么干净利落呢?

小智 67

您可以使用 _.compact(array);

创建一个删除了所有falsey值的数组.值false,null,0,"",undefined和NaN都是假的.

请参阅:https://lodash.com/docs/4.15.0#compact

  • 在这种情况下,您的答案无效,因为问题表明需要保留空值... (22认同)

Pio*_*łek 33

使用lodash的最佳方法是_.without

例:

const newArray = _.without([1,2,3,undefined,0,null], undefined);
Run Code Online (Sandbox Code Playgroud)


epa*_*llo 8

不需要具有现代浏览器的库.过滤器内置.

    var arr = [ 1, 2, 3, undefined, 0, null ];
    var updated = arr.filter(function(val){ return val!==undefined; });
    console.log(updated);
Run Code Online (Sandbox Code Playgroud)


Rya*_*all 7

使用lodash,你可以做到:

var filtered = _.reject(array, _.isUndefined);

如果你也想过滤null,以及undefined在某些点:

var filtered = _.reject(array, _.isNil);


JLa*_*oie 5

使用lodash,以下内容仅从数组中删除未定义的值:

var array = [ 1, 2, 3, undefined, 0, null ];

_.filter(array, function(a){ return !_.isUndefined(a) }
--> [ 1, 2, 3, 0, null ]
Run Code Online (Sandbox Code Playgroud)

或者,以下将删除undefined,0和null值:

_.filter(array)
--> [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

如果要从数组中删除null和undefined值,但保持值等于0:

_.filter(array, function(a){ return _.isNumber(a) || _.isString(a) }
[ 1, 2, 3, 0 ]
Run Code Online (Sandbox Code Playgroud)