Remove, delete or turn null specific elements in a 2D array

73 Views Asked by At

I'm trying to utilize splice to create a copy of an array with the elements from a certain position determined by the position of the current cell in a spreadsheet and pass those on to the splice function to remove the elements from a specified position to the end of the array. E.g. if the current column is in the 6th row and 4th column, all elements in the array from that position are deleted:

/**
* @customfunction
*/
function custom_function5() 
{

  var spreadSheet = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/16li86UxKwDl4LUzgEdpfWdbZuDYcZ0t-adNJN56-bzQ/edit?pli=1#gid=0');
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Scratch Pad");
  var currentCellRowIndex = SpreadsheetApp.getCurrentCell().getRow();
  Logger.log("The values are " + currentCellRowIndex);
  var currentCellColumnIndex = SpreadsheetApp.getCurrentCell().getColumn();
  Logger.log("The values are " + currentCellColumnIndex);
  var array1 = sheet.getRange(6, 2, currentCellRowIndex, 6).getValues();
  Logger.log("The array values are " + array1);
  var array2 = array1[currentCellRowIndex].splice(currentCellColumnIndex - 1, 6 - currentCellColumnIndex); 
  Logger.log("The array2 values are" + array2);

}

[Spreadsheet][1]

I'm getting the following error: ReferenceError: array1 is not defined [1]: https://docs.google.com/spreadsheets/d/16li86UxKwDl4LUzgEdpfWdbZuDYcZ0t-adNJN56-bzQ/edit?pli=1#gid=0

1

There are 1 best solutions below

1
Century Tuna On

UPDATED. Try this:

  function myFunction() {
  var ss = SpreadsheetApp.getActive().getActiveCell();
  var sheet = SpreadsheetApp.getActive().getActiveSheet().getRange("B6:G13");
  var table = sheet.getValues();
  var startRow = 6; //define start row
  var startCol = 2; //define start col
  var arrayColPosition = ss.getColumn() - startCol;
  var arrayRowPosition = ss.getRow() - startRow;
  var trigger = false;

  console.log("Selection Column: "+arrayColPosition, "\nSelection Row: "+arrayRowPosition);

  var finalTable = table.map((r, i) => i == arrayRowPosition ? r.map((y, c) => c == arrayColPosition ? y[arrayColPosition] = '*' : y) : r);

  console.log(finalTable);

  var res = finalTable.map((r, indexRow) => r.map((c, indexColumn) => {
    if(c == '*') trigger = true;
    if(indexColumn >= arrayColPosition && trigger || indexRow > arrayRowPosition ){
      return '';
    }else{
      return c;
    }
  }));

  sheet.setValues(res);
}

The active cell will set a placeholder " * " and from there it will delete the remaining data on the table.

GIF:

enter image description here