I showed this script to a co-worker and he provided me with some insight.
"it looks to me like when sorting townList you end up losing your indexed association with the 'town' array. So you must store the index of the town along with the name of the town; then sort by the name while still keeping a hold of what index it is in `town`."
He was able to give me a script back that accomplished what he recommended, but it still didn't quite work.
We compared his script, that was based off yours, and then compared and stole things from the original script that was sorting the layers themselves (see original code above) but not the path items.
We then put everything together and got it working with this!
#target "Illustrator" function alphabetize() { if (app.documents.length == 0) { alert("No document Open"); return; } var docRef = app.documents[0]; var state = docRef.layers; for (a = 0; a < state.length; a++) { var provider = state[a].layers; for (b = 0; b < provider.length; b++) { var product = provider[b].layers; for (c = 0; c < product.length; c++) { var town = product[c].pathItems; if (town.length > 0) { var townList = []; for (d = 0; d < town.length; d++) { townList.push(town[d].name); } townList.sort(); sort_layer(product[c], townList); } } } } } function sort_layer (obj, array) { for (var ri=0, riL=array.length; ri < riL ; ri++) { obj.pathItems.getByName(array[ri]).zOrder( ZOrderMethod.SENDTOBACK ); }; } alphabetize();