Ugh -- what a dumb bug. When you don't sort the TOC by artist, everything comes out as expected -- sorted by page number. But sorting the level-1 entries (artists) messes up the order of the level-2 entries (titles). So you can sort a TOC correctly only if there is just one level.
In your case you should really mark up the artists and titles with index markers, so you get exactly what you're after. You's need one or two scripts to mark up the document, but that's a one-off. Adding index markers is simple enough, but because artiist and title are in separate frames it's not so straightforward. Can be done though.
For now, though, sticking to the TOC is simpler. Like before, use the earlier script to remove duplicate artist names. Then use the script, below, to sort the titles by page number. Place the cursor in any title, then run the script.
One thing I noticed just now is that titles are sorted by page number only: if there are two or more titles on the same page, those titles aren't sorted automatically.
// Place the cursor in a paragraph
// on whose name you want to sort the list
(function () {
app.findGrepPreferences = null;
app.findGrepPreferences.appliedParagraphStyle =
app.selection[0].appliedParagraphStyle;
var story = app.selection[0].parentStory;
if (story.characters[-1].contents != '\r') {
story.insertionPoints[-1].contents = '\r';
}
var temp = app.documents[0].textFrames.add ({
geometricBounds: [0, 0, '50mm', '50mm'],
});
function sortBlock (block) {
var i;
var index = block.index;
var a = [];
var p = block.paragraphs.everyItem().getElements();
for (i = 0; i < p.length; i++) {
a.push ({
text: p[i],
key: Number (p[i].contents.match (/\d+(?=\r)/)[0]),
});
}
a.sort (function (a, b) {return a.key - b.key});
for (i = 0; i < p.length; i++) {
a[i].text.duplicate (
LocationOptions.AT_END,
temp.parentStory
);
}
block.remove();
temp.parentStory.move (
LocationOptions.AFTER,
story.insertionPoints[index]
);
}
var titles = app.selection[0].parentStory.findGrep();
for (var i = titles.length-1; i >= 0; i--) {
if (titles.length > 1) {
sortBlock (titles[i]);
}
}
while (story.characters[-1].contents == '\r') {
story.characters[-1].contents = '';
}
temp.remove();
}());