从嵌套数组中过滤出空字符串

时间:2020-10-31 07:44:13

标签: javascript

我有一个这样的数组数组:

let arr = [
      ["do you ever", "have you ever", "worried"],
      ["another", ""],
      ["about"],
      ["the notion"],
      ["that"],
      ["did you ever"],
      [""]
];

我需要从嵌套数组和作为结果变为空的嵌套数组中删除空字符串。例如,

[ ["do you ever", "have you ever", "worried"],
  ["another"],
  ["about"],
  ["the notion"],
  ["that"],
  ["did you ever"]
];

4 个答案:

答案 0 :(得分:2)

您可以按照以下方式尝试使用Array.prototype.map()Array.prototype.filter()

let arr = [
      ["do you ever", "have you ever", "worried"],
      ["another", ""],
      ["about"],
      ["the notion"],
      ["that"],
      ["did you ever"],
      [""]
];
arr = arr.map(i => i.filter(i => i.trim())).filter(i => i.length);
console.log(arr);

答案 1 :(得分:2)

这是另一种实现方式:

let arr = [
      ["do you ever", ,"","have you ever", "worried"],
      ["another", ""],
      ["about"],
      ["the notion"],
      ["that"],
      ["did you ever"],
      [""]
];
arr = arr.map(a => a.filter(e => e !== "")).filter(e=> e.length !== 0)
console.log(arr)

答案 2 :(得分:1)

据我了解,您所有的数组(父数组和子数组)都可以减小大小。单独使用Array#filter是不可能的,并且Array#map不会减小数组的大小。

您可以为此使用Array#reduceArray#flatMap

在这种情况下,我会选择后者。它允许您取消嵌套在迭代过程中产生的子数组。这意味着您可以使用Array#flatMap来增长数组:

[1, 2].flatMap(n => [n, n]);
//=> [1, 1, 2, 2]

这意味着您也可以清空数组:

[1, 2].flatMap(n => []);
//=> []

两个示例都无法用Array#map完成。

因此,我们既可以用来变换数组的元素,也可以用来变换数组本身(即大小变大或变小):

const xs = [
      ["do you ever", "have you ever", "worried"],
      ["another", ""],
      ["about"],
      ["the notion"],
      ["that"],
      ["did you ever"],
      [""]
];

console.log(

  xs.flatMap(ys => {
    const zs = ys.filter(y => y !== "");
    return zs.length > 0 ? [zs] : [];
  })

)

答案 3 :(得分:0)

通过地图和过滤器的组合,您可以实现;

我假设arr仅包含数组,并且该数组包含字符串。否则,应该进行类型检查。

let arr = [
  ["do you ever", "have you ever", "worried"],
  ["another", ""],
  ["about"],
  ["the notion"],
  ["that"],
  ["did you ever"],
  [""]
];

arr.map(items => items.filter(_item => _item.length > 0)).filter(i => i.length > 0);