简体   繁体   English

删除或忽略数组中的空单元格

[英]Remove or ignore empty cells in array

I have tried every solution / code I've seen here and nothing worked.我已经尝试了我在这里看到的所有解决方案/代码,但没有任何效果。 Didn't change anything.没有改变任何东西。 I have a loop where I define my arrays.我有一个循环来定义我的数组。 Some cells are merged where I'm copying from and the array includes the empty columns as well.一些单元格在我复制的地方合并,数组也包括空列。

This is my code:这是我的代码:

var array = []; 
  for (var m = 0; m < startRows.length; m++) { 
    array[m] = sourceSheet.getRange(startRows[m],5,3,29).getValues().filter(String); 
  }
 // Logger.log("array:   " + array[0]);  

Why is this not working?为什么这不起作用?

Edit: Log of array[0]:编辑:数组[0]的日志:

[20-01-14 14:54:29:668 GMT] array:   Chlorine content,,,,,1 / d,,ASTM D5463,,,,,NSP601,,,Sat Dec 30 1899 14:05:00 GMT+0000 (Greenwich Mean Time),,0.42,,,,ppm,,,0.3 - 0.5,,,,,TREATED SEAWATER,,,,,,,,,,,,,,,,,,,,,,,,,,,,

First of all, you shouldn't use a loop to get the values from a Range.首先,您不应该使用循环从范围中获取值。 You can do the same with:你可以这样做:

var array = sourceSheet.getRange(startrow,5,3,29).getValues();

or if you are getting all the values of the Sheet:或者,如果您正在获取工作表的所有值:

var array = sourceSheet.getDataRange().getValues()

However, you can remove empty spots of an array with the splice function.但是,您可以使用splice函数删除数组的空位。 Since it's removing positions, the array will shrink every time it finds an empty spot, so the for loop used here has to go backwards:由于它正在删除位置,因此每次找到空位时数组都会缩小,因此此处使用的for循环必须向后移动:

  for (var i = array.length; i >= 0; i--){

    if (array[i] == ''){
      array.splice(i, 1); //i is the index, 1 is the number of positions to delete
    }

  }
  Logger.log(array);  

In case you declare and set the values for the array without the loop, it would be a 2D array, as you can see in the documentation .如果您在没有循环的情况下声明和设置array的值,它将是一个二维数组,如您在文档中所见。

 const arr = [ "Chlorine content", "", "", "", "", "1 / d", "", "ASTM D5463", "", "", "", "", "NSP601", "", "", "Sat Dec 30 1899 14:05:00 GMT+0000 (Greenwich Mean Time)", "", "0.42", "", "", "", "ppm", "", "", "0.3 - 0.5", "", "", "", "", "TREATED SEAWATER", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" ]; const result = arr.filter(el => el); console.log(result)

If this is your array, that means that you can filter the empty values using a simple filter, instead of .filter(String)如果这是您的数组,则意味着您可以使用简单的过滤器而不是.filter(String)过滤空值

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

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