如何基于指定书签对象递归排序多层级JS树形文件结构
实现方案
核心思路
- 先处理当前层级的文件排序,再递归处理每个文件的子内容
- 提前将当前层级书签的名称与顺序、子章节的映射关系存入Map,避免排序时重复遍历,提升执行效率
- 未出现在书签中的文件会默认排在当前层级的末尾
完整实现代码
// 先定义对应类型,可根据你的实际业务结构调整 interface File { info: { name: string }, contents: File[], isHidden: boolean } interface BookmarkItem { part?: string, name?: string, chapters: BookmarkItem[] } /** * 按书签结构递归排序文件树 * @param files 待排序的文件数组 * @param bookmark 当前层级对应的书签数组 */ export function sortFilesByBookmark(files: File[], bookmark: BookmarkItem[]) { // 生成当前层级的「名称-排序索引」、「名称-子书签列表」映射 const orderMap = new Map<string, number>() const childBookmarkMap = new Map<string, BookmarkItem[]>() bookmark.forEach((item, index) => { // 顶层书签字段为part,子层级字段为name,统一取存在的值作为匹配名 const itemName = item.part ?? item.name if (itemName) { orderMap.set(itemName, index) childBookmarkMap.set(itemName, item.chapters) } }) // 排序当前层级的文件 files.sort((a, b) => { // 不存在于书签中的项默认排在最后,索引设为无穷大 const indexA = orderMap.get(a.info.name) ?? Infinity const indexB = orderMap.get(b.info.name) ?? Infinity return indexA - indexB }) // 递归处理每个文件的子内容 files.forEach(file => { const childBookmark = childBookmarkMap.get(file.info.name) // 只有当前文件有子内容、且对应书签有子章节配置时才执行递归排序 if (file.contents?.length && childBookmark?.length) { sortFilesByBookmark(file.contents, childBookmark) } }) }
使用示例
// 数组sort为原地修改方法,调用后会直接变更原files数组的顺序 sortFilesByBookmark(files, bookmark)
内容的提问来源于stack exchange,提问作者Dzsonah
相关产品推荐
相关产品推荐

