如何从嵌套数组中删除空值 [英] How to remove null values from nested arrays

查看:84
本文介绍了如何从嵌套数组中删除空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码从数组中删除所有空值:

This code removes all null values from array:

var array = [ 0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,, ];

var filtered = array.filter(function (el) {
  return el != null;
});

console.log(filtered);

但是,当我在具有空值的嵌套数组的数组上尝试此操作时,不会删除空值:

But when I try this on an array with nested arrays that have null values, the nulls are not removed:

var array = [ [ 1, null, 2 ], [ 3, null, 4 ], [ 5, null, 6 ] ];

var filtered = array.filter(function (el) {
  return el != null;
});

console.log(filtered);

预期输出为:

[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]

而不是实际输出:

[ [ 1, null, 2 ], [ 3, null, 4 ], [ 5, null, 6 ] ]

如何更改示例以从中过滤空值嵌套数组?

How can I change my example to filter null values from the nested arrays?

推荐答案

如果您的数组只有一层,那么您只需 map 就像这样:

If your array-of-arrays only has one level, then you can just map it like this:

var filtered = array.map(subarray => subarray.filter(el => el != null));
console.log(filtered);

这篇关于如何从嵌套数组中删除空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆