Google Sheets custom function to join cell range values with comma separator

I’m working on a Google Apps Script function that needs to take a cell range as input and combine all the values into one text string with commas between them.

Let’s say I have data in range D3:D5 where:

  • D3 has “Apple”
  • D4 has “Orange”
  • D5 has “Banana”

I want my custom function to output: “Apple, Orange, Banana”

function combineValues(dataRange) {
  // Need help implementing this
  var result = "";
  // How do I loop through the range and join with commas?
  return result;
}

What’s the right way to iterate through the range and concatenate the cell contents with comma delimiters in Google Apps Script?

try using dataRange.flat().filter(cell => cell).join(', ') - much cleaner than looping. the flat() method converts the 2d array to 1d and filter removes empty cells automatically

You can simplify this by using getValues() method which returns the 2D array, then directly manipulate it. I’ve been using this approach for similar data consolidation tasks:

function combineValues(dataRange) {
  var data = dataRange.getValues();
  var result = data.map(function(row) {
    return row[0];
  }).filter(function(cell) {
    return cell !== "";
  }).join(", ");
  return result;
}

The map function extracts the first column value from each row, filter removes any empty strings, and join concatenates everything with comma spacing. This handles both single column ranges and prevents issues with undefined values that sometimes occur when ranges contain mixed data types.

I ran into this exact scenario a few months back when building a function to consolidate product names from inventory sheets. The key thing to remember is that Google Sheets passes ranges as 2D arrays to your custom function, even for single columns. Here’s what worked for me:

function combineValues(dataRange) {
  var values = [];
  for (var i = 0; i < dataRange.length; i++) {
    if (dataRange[i][0] !== "") {
      values.push(dataRange[i][0]);
    }
  }
  return values.join(", ");
}

The dataRange[i][0] syntax accesses the first column of each row since ranges are always 2D arrays. I added the empty check because it prevents blank cells from creating extra commas in your output string. This approach handles variable range sizes automatically without needing to hardcode cell counts.