Question

Please help a G.A.S. newbie out! I've got a spreadsheet I'm working with, and I'm triggering this script from one cell of the spreadsheet and having it analyze another column. I've been having it simply return the keyword I want it to put in the analysis column, but some of my data will have multiple keywords.

It seems to me that the easiest thing to do is to simply concatenate—add the relevant new keyword to what is currently in that cell of the spreadsheet. However, I'm not finding much about concatenating returned values. Do I need to create an array or something to facilitate this, and then have it return the array as a string after the whole script has run?

Here's the code I'm working with:

function proteins(inCell){
      if(inCell.toString().match('chicken') == 'chicken') {
        return 'chicken';}
  else if(inCell.toString().match('mortadella') == 'mortadella') {
    return 'pork';}
     else if(inCell.toString().match('beef') == 'beef') {
        return 'beef';}
      else if(inCell.toString().match('pork') == 'pork') {
        return 'pork';}
      else if(inCell.toString().match('ham') == 'ham') {
        return 'pork';}
  else {return 'something else';}
}

Thank you for your time!

Was it helpful?

Solution

The problem is that when you use return 'pork' or whatever return, your function actually returns, ie quits the function and never examine the other conditions. The solution is simple : use a separate variable to concatenate results and return that variable at the end of the function. Something like this :

function proteins(inCell){
  var result = '';    
  if(inCell.toString().match('chicken') == 'chicken') {
    result += 'chicken';}
  else if(inCell.toString().match('mortadella') == 'mortadella') {
    result += 'pork';}
  else if(inCell.toString().match('beef') == 'beef') {
    result += 'beef';}
  else if(inCell.toString().match('pork') == 'pork') {
    result += 'pork';}
  else if(inCell.toString().match('ham') == 'ham') {
    result += 'pork';}
  else {result += 'something else';}
  return result;
}

This will return all the valid strings put together, you might want to add separators for readability then simply add a comma or an hyphen after each item you add...

And if you really want it to be perfect, remove the last comma before returning the result using a simple javascript string function. See doc here for example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top