JS实现将不在fileStructure中的文件树元素移至files数组末尾
问题原因
- 遍历数组时直接修改原数组结构:你使用
for...of遍历的同时调用splice删除元素,会导致数组索引动态偏移,后续遍历会跳过部分元素,因此仅能处理少量不符合要求的元素。 - 未处理嵌套结构:当前代码仅处理了最外层的文件数组,没有递归处理文件内部
contents字段里的子层级条目,因此文件夹内的未匹配元素不会被移动。
修复方案
我们可以把每一层的元素拆分为「匹配到fileStructure的元素」和「未匹配到的元素」两部分,再将未匹配部分拼到当前层级末尾,同时递归处理所有嵌套的contents字段,避免修改正在遍历的数组:
type FileType = { info: { name: string }, contents: FileType[] } type FilesStructure = { title: string, chapters: FilesStructure[] } export function placeUnIncludedElementsAtTheEndOfTheSortedArray( sortedArray: FileType[], fileStructure: FilesStructure[], ): FileType[] { // 拆分当前层级:匹配的元素 + 未匹配的元素 const matched: FileType[] = [] const unmatched: FileType[] = [] // 用Set存结构名称实现O(1)快速查找 const structureTitleSet = new Set(fileStructure.map(item => item.title)) for (const file of sortedArray) { if (structureTitleSet.has(file.info.name)) { matched.push(file) // 递归处理当前文件的子层级内容 const curStructure = fileStructure.find(item => item.title === file.info.name) if (curStructure && file.contents.length) { file.contents = placeUnIncludedElementsAtTheEndOfTheSortedArray(file.contents, curStructure.chapters) } } else { unmatched.push(file) } } // 匹配项在前,未匹配项在后拼接返回 return [...matched, ...unmatched] }
调用该函数传入你提供的files和filesStructure参数,即可得到符合要求的输出结果:外层未匹配的文件移到数组末尾,文件夹内部未匹配的章节也会移到对应文件夹的contents末尾。
内容的提问来源于stack exchange,提问作者Dzsonah
相关产品推荐
相关产品推荐

