Google Sheets: Merge Non-Zero Values in Row with Column Header

concatenategoogle sheetsgoogle-apps-script

I hope this example is clear. I have played with join and filter but can't get the Summary field to display as below:

Example

Row 1 is a list of subjects.
Row 2 is a teacher's subject allocation (calculated from a lookup).
I want the Summary cell to simply work through each row, if there is a non-zero value in a cell, take that number and concatenate to the subject, then move on to the end of the list.

Happy to try a script.

Best Answer

With the following piece of code you can prepare the summary as you want.

Code

function mySummary(header, range) {
  var output1 = [];
  for(var i=0, iLen=range.length; i<iLen; i++) {
    var output2 = [];
    for(var j=0, jLen=range[0].length; j<jLen; j++) {
      var value = range[i][j];
      if(value != "" || value > 0) {
        output2.push(value + " " + header[0][j]);
      }     
    }
    output1.push([output2.sort().join(", ")]);
  }
  return output1;  
}

Screenshot

enter image description here

Explained

The custom function needs two parameters to work with: header & range. The first iteration (var i=0) handles the rows and the second (var j=0) handles the columns. Each cell will be evaluated for empty ("") or non-zero (> 0) values. When either of them is true, the result is pushed into an intermediate array (output2). When the first row is completed, the combined result is sorted and joined and pushed into a new output array (output1), before starting with the second row.

Example

I've created an example file for you: Special Summary
Add the script under Tools>Script editor and press the save button.