Here’s how to sort bookmarks into position order in a document.  We’ll use Advanced Array functions heavily here.


First we get the bookmarks positions and the elements they refer to, and add a path to them to identify where they occur in the document. These paths will look something like this – here they are sorted. I make use of the childIndex method to get where an element is relative to its parent, and recursively go back up through the document to create a sortable index for each bookmark in the document, and then sort it using this generated path. Finally I get rid of the sorting aid, and get back to an array of bookMarks – this time sorted in the order they appear in the document.

The code

The Test

To use this create a document with various paragraphs, list items, tables etc, some of which contain the target words or phrases, run this and check the log to ensure the bookmarks get sorted according to document order.
For more like this see Google Apps Scripts Snippets
For help and more information join our forum, follow the blog, follow me on Twitter