Organizing Your Google Docs with Apps Script: A Guide to Sorting Sections by Headings

When working on large Google Docs, organizing content systematically can be daunting, especially if you’re dealing with sections categorized under specific headings. This is where Google Apps Script comes to the rescue! In this blog post, we’ll explore a function, reorganizeDocByHeading2, that reorganizes the content of a Google Doc based on predefined categories under “Heading 2” style. Let’s dive into how this script works and how you can use it to keep your documents neat and structured.


Understanding the Purpose

This script:

  • Extracts all sections under “Heading 2” in a Google Doc.
  • Sorts them according to a predefined order (categoriesOrder array).
  • Reconstructs the document with the sorted sections.

It’s especially useful for educators, technical writers, or anyone managing large, structured documents like tutorials, manuals, or FAQs.


The Code

Here’s the complete script:

function reorganizeDocByHeading2() {
const categoriesOrder = [
"Basics of JavaScript",
"Beginner Questions",
"Control Structures",
"Functions",
"Intermediate Questions",
"DOM Manipulation",
"ES6+ Features",
"Error Handling",
"Asynchronous Programming",
"Advanced Questions",
"Closures",
"Functional Programming",
"Object-Oriented Programming",
"Design Patterns",
"Performance Optimization",
"Modules and Imports",
"Miscellaneous Advanced Topics"
];

const doc = DocumentApp.openById(DOCID);
const body = doc.getBody();
const allContent = [];

// Extract content under each Heading 2
let currentSection = { heading: "", content: [] };
const paragraphs = body.getParagraphs();

paragraphs.forEach(paragraph => {
if (paragraph.getHeading() === DocumentApp.ParagraphHeading.HEADING2) {
// Save current section if it exists
if (currentSection.heading) {
allContent.push(currentSection);
}
// Start new section
currentSection = { heading: paragraph.getText(), content: [] };
} else if (currentSection.heading) {
// Add paragraph to the current section
currentSection.content.push(paragraph.copy());
}
});
// Add the last section if it exists
if (currentSection.heading) {
allContent.push(currentSection);
}

// Sort sections based on the predefined order
allContent.sort((a, b) => {
const indexA = categoriesOrder.indexOf(a.heading);
const indexB = categoriesOrder.indexOf(b.heading);
return indexA - indexB;
});

// Clear the document
body.clear();

// Rebuild the document with sorted content
allContent.forEach(section => {
body.appendParagraph(section.heading).setHeading(DocumentApp.ParagraphHeading.HEADING2);
section.content.forEach(paragraph => body.appendParagraph(paragraph));
body.appendParagraph(""); // Add space between sections
});

Logger.log("Reorganization completed!");
}

How It Works

  1. Categories Definition
    The categoriesOrder array defines the desired order of the headings. Modify this list to fit your specific needs.
  2. Extracting Content
    The script scans the document for paragraphs styled as “Heading 2.” For each heading found, it collects the content that follows until the next “Heading 2.”
  3. Sorting Sections
    The collected sections are sorted based on their position in the categoriesOrder array. Headings not listed in the array will remain in their original order.
  4. Rebuilding the Document
    After sorting, the document is cleared, and the sorted sections are appended back, ensuring the content follows the specified order.

How to Use This Script

  1. Set Up Google Apps Script
    • Open Google Docs.
    • Navigate to Extensions > Apps Script.
    • Replace any existing code with the script above.
  2. Replace DOCID
    • Replace DOCID with the ID of your Google Doc. The document ID is found in the URL of your Google Doc (e.g., https://docs.google.com/document/d/DOCID/edit).
  3. Run the Script
    • Save the script and run it by clicking the play button ▶️ in the Apps Script editor.
    • Grant necessary permissions when prompted.

Applications and Benefits

  • Streamlined Organization: Ideal for tutorials, FAQs, or documents with hierarchical content.
  • Customizable Categories: Tailor the categoriesOrder array to match your document structure.
  • Saves Time: Automates the tedious process of reorganizing content manually.

Final Thoughts

Google Apps Script is a powerful tool for enhancing productivity in Google Workspace. By automating repetitive tasks like content organization, you can focus on the creative aspects of your work. Give this script a try, and let us know how it helped streamline your workflow!