简体   繁体   中英

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]:

[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. 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 (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 .

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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