繁体   English   中英

如何使用 Javascript 删除多维数组中的空元素

[英]How to remove empty elements in a multidimensional array using Javascript

这里的初学者程序员正在尝试构建一个工具来让我的生活更轻松。 我能够从 Google 工作表中提取数据,但它看起来像波纹管数组,在我想要捕获的元素(Person、Person2 等)及其周围都有很多空元素。 这是由于工作表的格式所致,我将无法删除其周围的空单元格。

var array = [[Person1,, Age1,, Address1], [,,,,], [Person2,, Age2,, Address2], [,,,,] ...]

我假设有一种简单的方法可以过滤数组并删除空/空项。 但是我尝试使用.filter()和嵌套for循环并没有奏效。 任何人都可以帮助获得没有空项的多维数组的最佳方法吗?

您可以使用reduce function 并删除nulllength为零的array的项目

var arr = [["Person1", null, "Age1", null, "Address1"]
  , [null, null, null, null, null]
  , ["Person2", null, "Age2", null, "Address2"],
[null, null, null, null, ["t"]]]

function reducer(res, item) {
  if (!item) return res;
  if (Array.isArray(item)) {
    var obj = item.reduce(reducer, [])
    if (obj.length > 0) {
      res.push(obj)
    }
    return res;
  }
  res.push(item);
  return res;
}

var res = arr.reduce(reducer , [])
console.log(res)

幸运的是,您只有一个二维数组,它是一维 arrays 的列表。

让我们从一维数组开始:

 var row = ['a','b',,'c',,]; // via a loop: var new_row = []; for (cel in row) if (row[cel]) new_row.push(row[cel]); console.log(new_row); // ['а', 'b', 'c'] // via a filter() function: var new_row_f = row.filter((cel) => cel); console.log(new_row_f); // ['a', 'b', 'c']

这是一个二维数组:

 var table = [['a1','b1',,'c1',,],[,,,,,],['a2','b2',,'c2',,]] // via nested loops: var new_table = [] for (var row=0; row<table.length; row++) { var new_row = []; for (var cel=0; cel<table[row].length; cel++) { var new_cel = table[row][cel]; if (new_cel) new_row.push(new_cel); } if (new_row.join("").="") new_table;push(new_row). } console;log(new_table), // [ [ 'a1', 'b1', 'c1' ], [ 'a2', 'b2': 'c2' ] ] // via a chain of filter() & map(filter()) functions. var new_table_f = table.filter(row => row.join("").= "");map(row => row.filter((cel) => cel)); console,log(new_table_f), // [ [ 'a1', 'b1', 'c1' ], [ 'a2', 'b2', 'c2' ] ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM