Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsmap-function

Map() function not giving expected results Google script


I am trying to learn how to use Map(), in the function below Method1, the function runs i.e it executes and does not throw an error but it does not change any cell values equal to Networking - 1 to 1 it leaves the data unchanged

I am not understanding what is not working.

function Method1() {
  var ss     = SpreadsheetApp.getActiveSpreadsheet();  
  var sheet  = ss.getSheetByName('Elements');  
  var rng    = sheet.getDataRange();
  var values = rng.getValues();
  
  values = values.map(x => {return x = (x=="Networking - 1" ) ? 1: x;});

  sheet.getRange(1,1, values.length, values[0].length).setValues(values);
}

Solution

  • Issue / Explanation:

    • The issue is that values is a 2D array and when you are using a single map x represents a row. You can't compare a row with a single value. It wouldn't make sense to compare something like ['','',''] with ''. Therefore, you need to find a way to get every element of this array and compare that against the string value.

    • My approach would be to use a map inside of another map function. The first map will get the rows and the second one the elements of each row and compare them against the string:

      values = values.map(x => x.map(y=>y=="Networking - 1"  ? 1: y))
      

      x will be the row and y will be an element in that row. In this way you compare an element with a single value "Networking - 1".

    • When you use a single line in map and in other similar array functions you don't need to use return and {}. Also you want to return the returned value, not the assignment operation.

    Solution:

    function Method1() {
      var ss     = SpreadsheetApp.getActiveSpreadsheet();  
      var sheet  = ss.getSheetByName('Elements');  
      var rng    = sheet.getDataRange();
      var values = rng.getValues();
      values = values.map(x => x.map(y=>y=="Networking - 1"  ? 1: y))
                          
      sheet.getRange(1,1, values.length, values[0].length).setValues(values);
    }