首页 > 解决方案 > 如何从嵌套数组中删除空元素

问题描述

我命名了以下数组parsedAutor,我需要从嵌套数组中删除空元素。

[
  ['John Doe', '', 'CPF 000.000.000-00'],
  ['30/05/2018 - Vara de Delitos de Roubo e Extorsão'],
  ['John Doe', '', 'CPF 000.000.000-00'],
  ['29/02/2016 - 1ª Vara Criminal'],
  ['John Doe', '', 'CPF 000.000.000-00'],
  ['18/02/2016 - 3º Juizado Especial Cível'],
  ['John Doe', '', 'CPF 000.000.000-00'],
  ['18/02/2016 - 3º Juizado Especial Cível']
]

我该如何做到这一点?我一直在尝试映射元素然后过滤它们,但它不起作用,我认为我做错了。

这就是我一直在尝试做的事情。

const autor = $('div[class="espacamentoLinhas"]').toArray();

let parsedAutor = autor.map((x) => x.children[2].data.trim());

console.log(parsedAutor);

parsedAutor = parsedAutor.map((x) => x.split('\n').map((y) => y.trim()));

console.log(parsedAutor);

// note that the code above is just to get the context from where I taking the values,  please focus on the code below

const filteredAutor = parsedAutor.map((x) => {
  x.filter((y) => y !== '');
});

console.log(filteredAutor);

但它返回了八个undefined值,我做错了什么?

提前致谢。

标签: javascriptnode.js

解决方案


您的代码几乎是正确的!您需要在 x 上返回过滤器,或缩短它。

const filteredAutor = parsedAutor.map((x) => x.filter((y) => y !== ''));

或者

const filteredAutor = parsedAutor.map((x) => {
    return x.filter((y) => y !== '');
});

推荐阅读