I was looking at it another way, incrementing the counter for the unique values of `${$feature.Field1}-BB-`
I haven't tested it, but was thinking along these lines
var fs = FeatureSetByName($datastore, "yourLayer");
var sql = `${$feature.Field1}-BB-`;
var filtered = Filter(fs, "Field2 LIKE @sql");
if (Count(filtered) == 0) return `${$feature.Field1}-BB-1`;
var list = [];
for (var f in filtered) {
Push(list, f["Field2"]);
}
function reverseSort(a, b) {
if (a < b) return 1;
if (a > b) return -1;
return 0;
}
var highest = Sort(list, reverseSort)[0]
return `${$feature.Field1}-BB-${Number(Split(highest, "-BB-")[1])+ 1}`
In line 3, the FeatureSet is filtered to only show the existing values for that field. If there aren't any, it returns the string with the counter = 1 in line 4.
Lines 6-9 create a list of the values in Field2. Lines 11-15 are a reverse sorting function (taken from the Sort example) to get the highest value in line 17. Line 18 returns the string and the highest value incremented by one.