For this example you need an “index” placeholder and other placeholders to output the record data. Add both in separate lines but without additional empty lines between them (the script will take care of that).
Give the index placeholder a generation chain and in the generation chain settings choose “Delete line” as last action. Then if no index letter is created, the index placeholder and its whole line will be removed. Add a custom script element, fill in the script below and adjust it to your needs.
To output all of your data in one text frame choose “inline merge” in export > multiple records.