google-sheetsgoogle-apps-script

Delete last row with value then find


I have a google script that delete row that contain value of active cell

function deleteshift() {
let ss = SpreadsheetApp.getActiveSpreadsheet();
let sheet = ss.getSheetByName('main');
let dataSheet = ss.getSheetByName('deletDB');
let existingId = sheet.getActiveCell().getValue();
let existing = dataSheet.getRange(2,6,dataSheet.getLastRow()-1).getValues().flat();
let index = existing.indexOf(existingId);

if (index != -1) { dataSheet.deleteRow(index + 2); } }

This script starts from the top row but how can I start from last row and delete the first entry from last to up.


Solution

  • Instead of indexOf, use lastIndexOf:

    const index = existing.lastIndexOf(existingId);