79289858

Date: 2024-12-18 02:59:15
Score: 1
Natty:
Report link

Further examination shows the problem isn't related to the order of bookmarks but because the code previously works from top to bottom.

Changing this

for (const [index, bookmark] of bookmarks.entries()) {
  // code
}

to this

for (const [index, bookmark] of bookmarks.reverse().entries()) {
  // code
}

solves the problem.

It's worth to note that when working with Position it's a good idea to always work from bottom to top, for good reasons.

==============

As for the order problem, I've created an example in github to workaround this issue.

The idea is to define the order yourself.

const config = [
  {
    imageName: 'Figure 1',
    bookmarkId: 'id.wglkb02zor96'
  },
  {
    imageName: 'Figure 2',
    bookmarkId: 'id.ifl1btgwoni'
  },
  {
    imageName: 'Figure 3',
    bookmarkId: 'kix.jithfpq0bbwm'
  }
];

Then use that order to work the bookmarks.

const docsId = '...';
const docs = DocumentApp.openById(docsId);
const doc = docs.getTabs()[0];
const bookmarks = doc.asDocumentTab().getBookmarks();

const bookmarkOrder = config.map(item => item.bookmarkId);
bookmarks.sort((a, b) => { // order bookmarks using config
  const indexA = bookmarkOrder.indexOf(a.getId());
  const indexB = bookmarkOrder.indexOf(b.getId());
  return indexA - indexB;
});

Alas, it's a shame that an important feature like bookmark is not well-behaved.

Reasons:
  • Contains signature (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Filler text (0.5): ==============
  • Low reputation (0.5):
Posted by: sangnandar