You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript数组内元素分组:按父层级分组数据结构问题

Group Chapters by Parent Level in JavaScript

Got it, let's solve this problem of grouping your flat chapter array into a nested structure based on their level values. Here's a practical, efficient approach that works for any depth of levels:

Step-by-Step Solution

1. Core Logic

We'll use a map to keep track of all nodes as we process them, making it easy to find parent nodes quickly. For each item:

  • Split its level string into an array of segments (e.g., '1.1.1' → ['1', '1', '1'])
  • Generate the parent level by removing the last segment (e.g., ['1', '1'] → '1.1')
  • Add the current item as a child to its parent node (we'll handle edge cases where a parent might be missing, though your data seems to have valid parent entries)

2. Code Implementation

const arr = [
  { level: '1.1', name: 'group title 1' },
  { level: '1.1.1', name: 'group section 1.1.1' },
  { level: '1.1.2', name: 'group section 1.1.2' },
  { level: '1.1.3', name: 'group section 1.1.3' },
  { level: '1.2', name: 'group title 2' },
  { level: '1.2.1', name: 'group section 1.2.1' },
  { level: '1.3', name: 'group title 3' },
  { level: '1.3.1', name: 'group section 1.3.1' }
];

function groupChaptersByParent(chapters) {
  const nodeMap = new Map();
  const root = { children: [] };

  chapters.forEach(chapter => {
    // Create a node for the current chapter, initialize an empty children array
    const node = { ...chapter, children: [] };
    nodeMap.set(chapter.level, node);

    // Split the level into segments to locate the parent
    const levelSegments = chapter.level.split('.');
    if (levelSegments.length > 1) {
      // Build the parent level string by removing the last segment
      const parentLevel = levelSegments.slice(0, -1).join('.');
      const parentNode = nodeMap.get(parentLevel);
      
      // Add current node to its parent's children list
      if (parentNode) {
        parentNode.children.push(node);
      } else {
        // Fallback: if parent doesn't exist, add to root (adjust this if needed)
        root.children.push(node);
      }
    } else {
      // Top-level chapters (like '1') get added directly to root
      root.children.push(node);
    }
  });

  // Return the top-level groups (1.1, 1.2, etc.) with their nested children
  return root.children;
}

// Test the function
const groupedChapters = groupChaptersByParent(arr);
console.log(JSON.stringify(groupedChapters, null, 2));

3. Output Result

When you run the code, you'll get a clean nested structure where each top-level group contains its child sections:

[
  {
    "level": "1.1",
    "name": "group title 1",
    "children": [
      { "level": "1.1.1", "name": "group section 1.1.1", "children": [] },
      { "level": "1.1.2", "name": "group section 1.1.2", "children": [] },
      { "level": "1.1.3", "name": "group section 1.1.3", "children": [] }
    ]
  },
  {
    "level": "1.2",
    "name": "group title 2",
    "children": [
      { "level": "1.2.1", "name": "group section 1.2.1", "children": [] }
    ]
  },
  {
    "level": "1.3",
    "name": "group title 3",
    "children": [
      { "level": "1.3.1", "name": "group section 1.3.1", "children": [] }
    ]
  }
]

Key Notes

  • This approach handles any depth of levels (e.g., 1.1.1.1 would automatically nest under 1.1.1)
  • The nodeMap ensures we look up parent nodes in O(1) time, making the overall process O(n) (super efficient even for large arrays)
  • If your data might have missing parent entries, the fallback adds those nodes to the root—you can tweak this logic to fit your specific use case

内容的提问来源于stack exchange,提问作者pro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:13:35