Starting point: I have a doc with sections separated by page breaks.
Goal: I want a Google Apps Script that scans through a doc and sorts the sections alphabetically (aka everything between a heading1 and a page break). The manual equivalent would be cut-pasting sections around until sorted.
To illustrate, here's an example document: initial state and desired end state.
So far, this is what I have:
A script that searches through a doc and identifies the headings with a given format (heading1). I could sort the headings alphabetically, but I don't know how to move whole sections around in the document.
function findHeading1s() {
let doc = DocumentApp.getActiveDocument();//.openById('<doc-id>');
var body = doc.getBody();
// Define the search parameters.
let searchType = DocumentApp.ElementType.PARAGRAPH;
let searchHeading = DocumentApp.ParagraphHeading.HEADING1;
let searchResult = null;
let headers = [];
// Search until the paragraph is found.
while (searchResult = body.findElement(searchType, searchResult)) {
let par = searchResult.getElement().asParagraph();
let parText = par.getText();
if (par.getHeading() == searchHeading && parText != "") {
headers.push(parText);
Logger.log(headers); //Headers in current order: [Zone, Template, Example]
}
}
Logger.log(headers.sort()) //[Example, Template, Zone]
}
Any ideas how to move everything between a heading and the following pagebreak? I don't mind if the sorted end result is in a new document.
Is this doable with existing GAS capabilities? Tried to debug the body/paragraph elements to get some idea on how to solve this, but I only get the functions of the object, not the actual content. Not super intuitive.
Here are the steps I think are needed:
- Identify heading1 headings ✅
- Sort headings alphabetically ✅
- Find each heading in the doc
- Cut-paste section in the appropriate position of the doc (or append to a new doc in the correct order)
Thanks!