本文介绍如何将混合字符串与对象的扁平数组,按字符串标题进行逻辑分组,并准确提取每个标题后跟随的所有对象,避免索引计算错误,提供两种实用结构化方案。
本文介绍如何将混合字符串与对象的扁平数组,按字符串标题进行逻辑分组,并准确提取每个标题后跟随的所有对象,避免索引计算错误,提供两种实用结构化方案。
在虚拟列表(virtualization)等场景中,常采用“标题 + 内容块”的扁平数组结构来兼顾渲染性能与语义清晰性。例如数组中交替出现字符串(作为分组标题)和对象(作为该标题下的数据项)。但直接使用 findIndex 配合 slice 容易因相对索引偏移、边界处理不当(如未考虑末尾无后续标题的情况)导致中间分组为空——正如原代码中 nextTitleIndex + 1 在 slice 中被错误地用于非相对起始位置,造成越界或空切片。
更稳健的做法是一次遍历、状态驱动:维护当前标题标识,动态累积内容,而非依赖反复搜索和复杂索引计算。以下是两种生产就绪的实现方式:
const result = [];test.forEach(item => { if (typeof item === 'string') { result.push([item]); // 新标题 → 新子数组,首项为标题本身 } else { // 确保至少有一个分组存在(防止非法输入) if (result.length > 0) { result[result.length - 1].push(item); } }});// 输出示例:// [// ["string 1", {prop1: "string 1 obj first"}, ..., {prop1: "string 1 obj last"}],// ["string 2", {prop1: "string 2 obj first"}, ..., {prop1: "string 2 obj last"}],// ...// ]
const result = {};let currentTitle = null;test.forEach(item => { if (typeof item === 'string') { currentTitle = item; result[currentTitle] = []; // 初始化空数组,确保 key 存在 } else if (currentTitle !== null) { result[currentTitle].push(item); }});// 输出示例:// {// "string 1": [{prop1: "string 1 obj first"}, ..., {prop1: "string 1 obj last"}],// "string 2": [{prop1: "string 2 obj first"}, ..., {prop1: "string 2 obj last"}],// ...// }
无论选择哪种结构,核心思想一致:用状态代替索引计算,用累积代替切片推导——简洁、可靠、易于维护。