Search code examples
javascriptgoogle-apps-scriptarrow-functions

Turn loop in to arrow function Javascript


I have a simple loop I want to turn into an arrow function

The function deletes all rows from the mainArray when there is a match in columns B or C with data in searchArray

removeROW_LOOP() works but removeROW_ARROW() does not

I get the error when running removeROW_ARROW() Exception: The number of columns in the data does not match the number of columns in the range. The data has 14 but the range has 21.

Thanks for any assistance with this

My data looks like mainArray enter image description here

searchArray

enter image description here

results

enter image description here

Loop (works)

function removeROW_LOOP() {
  var ss   = SpreadsheetApp.getActiveSpreadsheet();
  const searchArray = ss.getSheetByName('Helper_(ignore)').getDataRange().getDisplayValues().flat();
  const mainArray = ss.getSheetByName('Connections').getDataRange().getDisplayValues(); 
  let result = [];

  for (var i = 0; i <= searchArray.length-1; i++) {
     result = removeROW(mainArray, searchArray[i]);
  }

  const sht = ss.getSheetByName('AAA');
  sht.clear()  
  sht.getRange(1,1, result.length, result[0].length).setValues(result);
}

My attempt at arrow function (does not work)

function removeROW_ARROW() {
  var ss   = SpreadsheetApp.getActiveSpreadsheet();
  const searchArray = ss.getSheetByName('Helper_(ignore)').getDataRange().getDisplayValues().flat();
  const mainArray = ss.getSheetByName('Connections').getDataRange().getDisplayValues(); 

  const result = searchArray.map(s => removeROW(mainArray, s));

  const sht = ss.getSheetByName('AAA');
  sht.clear()  
  sht.getRange(1,1, result.length, result[0].length).setValues(result);
}

and

function removeROW(array, item) {
  array = array.filter(a => a[1]!=item && a[2]!=item);
  return array
}

Solution

  • I don't think the problem is function vs. arrow function. Your refactor actually changes the behavior significantly.

    removeROW_LOOP() will reset result upon each iteration with the newly filtered array. However, in removeROW_ARROW(), result will be an array of arrays. Specifically, each item in the result will be a filtered version of mainArray with only one searchArray entry filtered out of it.

    I think you want somthing along these lines:

    function removeUPDATED() {
      // ...
    
      const result = mainArray.filter(x => !searchArray.includes(x[0]) && !searchArray.includes(x[1]));
    
      // ...
    }
    

    I might have included a bug there, but I think it demonstrates the approach you want.