如何从数组中的数组中删除空值? [英] How do I remove null values from an array within an array?

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

问题描述

我正在使用Google表格和Google Apps脚本.我已经使用.getRange().getValues从工作表中获取用户电子邮件.

I am working with Google Sheets and Google Apps Scripting. I have used .getRange().getValues to grab user emails from a Sheet.

接收到的示例数组: [[user1, , ], [user2, user3, ], [user4, user5, user6]]

Example Array Received: [[user1, , ], [user2, user3, ], [user4, user5, user6]]

如您所见,每行(内部数组)最多可能有3个用户.但是,其中一些单元格为空,从而导致数组中的值为空.然后,我将每个内部数组输入.addEditors(),由于用户为空,这会引发错误.

As you can see, I have a potential of up to three users per row (inner array). However, some of those cells are empty resulting in empty values in the array. I am then feeding each inner array into .addEditors() which throws an error due to the empty user.

我知道我可以遍历每个数组并删除空对象,然后将该新数组推入.addEditors()中,但这将是很丑陋的,而且效率很低.我没有足够的经验来知道如何开发一种更优雅的方式.

I know I can run through each array and delete the empties and then push that new array into .addEditors() but it would be ugly, and very inefficient. I don't have enough experience to know how to develop a more elegant way.

有人可以帮助我了解如何以及为什么以尽可能有效的方式解决此问题吗?谢谢.

Could someone help me understand the how and the why to solve this issue in as efficient a manner as possible? Thanks.

注意:尽管看起来像 .filter(Boolean) 解决方案可能有效,我只能使它适用于单个数组,而不适用于数组中的一个数组.

Note: Though it seems like the .filter(Boolean) solution might work, I can only get it to work for a single array, not for an array within an array.

var myFilterArray = myArray.filter(Boolean);

    arr.forEach(function(x){
      return x.filter(Boolean);
    });

如果深度大于一,我无法获取它来返回修改后的数组.

I cannot get it to return the modified array if greater than one deep.

推荐答案

我知道我可以遍历每个数组并删除空容器 ...这几乎是您唯一的选择.有一些方法可以使您的代码看起来更整洁,但是在幕后必须要遍历整个数组.

I know I can run through each array and delete the empties... thats pretty much your only options. There are methods that make your code look cleaner but behind the scenes something is going to have to loop through the array.

以下是使用Array.map()Array.filter()

let data = [["bob", , ], ["jake", "john", ""], ["joe", "henry", "morgan"]];
let newData = data.map(x => {
  return x.filter(j => j)
})
console.log(newData);

使用ES5语法

var data = [["bob", , ], ["jake", "john", ""], ["joe", "henry", "morgan"]];
var newData = data.map(function(x) {
  return x.filter(function(j) {if (j) return j})
})
console.log(newData);

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

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