Search code examples
javascriptarraysgoogle-apps-scriptgoogle-sheetsgoogle-finance

Add text to the output of values of an array


I just started to learn Apps Script and I need to add some text to each value of an array. This code just puts the values in another column:

function getData() {
  var sheet1 = SpreadsheetApp.getActiveSpreadsheet()
      .getSheetByName("Stocks");
  var symbol = sheet1.getRange('A1:A7').getValues();
  sheet1.getRange('C1:C7').setValues(symbol);
}

I want to add some text to the output, like this:

function getData() {
  var sheet1 = SpreadsheetApp.getActiveSpreadsheet()
      .getSheetByName("Stocks");
  var symbol = sheet1.getRange('A1:A7').getValues();
  sheet1.getRange('C1:C7').setValues(
      '=GOOGLEFINANCE("FRA:' + symbol + ")'
  );
}

But I know that this won't work. How do I add to each value being written?


Solution

  • use a loop to go through your array of values

    function getData() {
      var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Stocks");
      var symbol = sheet1.getRange('A1:A7').getValues();
      var destRange = sheet1.getRange('C1:C7');
    
      for (var i = 0; i < symbol.length; i++)
        symbol[i][0] = '=GOOGLEFINANCE("FRA:' + symbol[i][0] + '")');
    
      destRange.setFormulas(symbol);
    }
    

    As range A1:A7 and C1:C7 are of same widht and height you can use back that array to then use setFormulas(array) of course use this method if you only use once symbol array if not then declare an empty array befor your loop as so :

    var resultArray = []
    

    then inside your for loop do:

     resultArray.push(['=GOOGLEFINANCE("FRA:' + symbol[i][0] + '")']);
    

    then use outside the for loop setFormulas():

    destRange.setFormulas(resultArray);