Sorting bookmarks in a document

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.

0000.0000.0000.
0000.0004.0000.
0000.0006.0000.0001.0000.0000.
0000.0008.0000.
0000.0010.0000.
0000.0012.0000.
0000.0012.0000.

The code