How to ignore empty cell values for getRange().getValues()
You want to achieve the following result.
Input
A1=abc A2=def A3= A4= A5= A6=uvw A7=xyz
Output
Browser.msgBox(range_input) // results = abc,def,uvw,xyz
In the current stage, I thought that although the comprehensions of var result = [i for each (i in range_input)if (isNaN(i))]
can be still used, it is not suitable for this situation as tehhowch's comment. Alto I think that filter()
is suitable for this situation. In this update, I would like to update this by proposing other solution. If this was useful, I'm glad.
Pattern 1:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Test");
var range_input = ss.getRange("A1:A").getValues();
var result = range_input.reduce(function(ar, e) {
if (e[0]) ar.push(e[0])
return ar;
}, []);
Logger.log(result) // ["abc","def","uvw","xyz"]
Browser.msgBox(result)
- In this pattern, the empty rows are removed by
reduce()
.
Pattern 2:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Test");
var range_input = ss.getRange("A1:A").getValues();
var result = [].concat.apply([], range_input).filter(String); // or range_input.filter(String).map(String)
Logger.log(result) // ["abc","def","uvw","xyz"]
Browser.msgBox(result)
- In this pattern, the empty rows are removed by
filter()
and whenfilter()
is used, the 2 dimensional array is returned. In order to return 1 dimensional array, the array is flatten.
Pattern 3:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Test");
var range_input = ss.getRange("A1:A").getValues();
var criteria = SpreadsheetApp.newFilterCriteria().whenCellNotEmpty().build();
var f = ss.getRange("A1:A").createFilter().setColumnFilterCriteria(1, criteria);
var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/gviz/tq?tqx=out:csv&gid=" + sheet.getSheetId() + "&access_token=" + ScriptApp.getOAuthToken();
var res = UrlFetchApp.fetch(url);
f.remove();
var result = Utilities.parseCsv(res.getContentText()).map(function(e) {return e[0]});
Logger.log(result) // ["abc","def","uvw","xyz"]
Browser.msgBox(result)
- In this pattern, the empty rows are removed by the filter, then the filtered values are retrieved.
Result:
References:
- reduce()
- filter()
- map()
- Class Filter
Not tested for efficiency, but for a simple removal of multiple ,
s, you can use regex:
const a=[['abc'],['def'],[''],[''],[''],['xyz'],['']];//simulate getValues()
const out = a.join(',').replace(/,+(?=,)|,*$/g,'') //'abc,def,xyz'
const out2 = a.join('«').replace(/«+$/,'').split(/«+/) //flattened
console.log({out, out2})
You can also use filter()
.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Test");
var range_input = ss.getRange("A1:A").getValues();
var filtered_input = range_input.filter(String);