如何截取数组至指定元素?JS混合数组标题间对象获取问题
问题解决:数组标题与对应对象分组提取
我有一个包含字符串(作为标题)和对象(作为对应内容)的数组,结构用于虚拟化场景,需要将每个标题与其后续直到下一个标题前的所有对象分组。当前实现的首尾迭代能正常获取对应对象,但中间迭代得到的对象数组为空。
原问题代码
const test = [ "string 1", { prop1: "string 1 obj first" }, { prop1: "string 1 obj" }, { prop1: "string 1 obj" }, { prop1: "string 1 obj" }, { prop1: "string 1 obj last" }, "string 2", { prop1: "string 2 obj first" }, { prop1: "string 2 obj" }, { prop1: "string 2 obj" }, { prop1: "string 2 obj last" }, "string 3", { prop1: "string 3 obj first" }, { prop1: "string 3 obj" }, { prop1: "string 3 obj" }, { prop1: "string 3 obj" }, { prop1: "string 3 obj" }, { prop1: "string 3 obj" }, { prop1: "string 3 obj last" }, ] const result = test.reduce((acc, curr, i, arr) => { const next = arr[i+1] // with Title if (typeof curr === 'string') { if (typeof next === 'object' && next !== null) { // get the index for the next title from here const nextTitleIndex = test.slice(i + 1).findIndex((item) => typeof item === 'string'); // slice the array from this point up to the index of the next title (not included) const objects = test.slice(i + 1, nextTitleIndex === -1 ? undefined : nextTitleIndex + 1) console.log({ nextTitleIndex, objects }) } } return acc }, [])
问题原因
问题出在索引转换错误:
test.slice(i + 1).findIndex(...)返回的是切片后子数组的相对索引,不是原数组的绝对索引- 后续计算
slice的结束位置时,直接用nextTitleIndex + 1,导致中间迭代时结束位置小于起始位置(比如处理"string 2"时,结束位置计算错误,得到空数组)
修正后的代码
将相对索引转换为原数组的绝对索引,再进行切片:
const test = [ "string 1", { prop1: "string 1 obj first" }, { prop1: "string 1 obj" }, { prop1: "string 1 obj" }, { prop1: "string 1 obj" }, { prop1: "string 1 obj last" }, "string 2", { prop1: "string 2 obj first" }, { prop1: "string 2 obj" }, { prop1: "string 2 obj" }, { prop1: "string 2 obj last" }, "string 3", { prop1: "string 3 obj first" }, { prop1: "string 3 obj" }, { prop1: "string 3 obj" }, { prop1: "string 3 obj" }, { prop1: "string 3 obj" }, { prop1: "string 3 obj" }, { prop1: "string 3 obj last" }, ] const result = test.reduce((acc, curr, i, arr) => { if (typeof curr === 'string') { // 从当前索引的下一位开始找下一个标题的相对索引 const nextTitleRelativeIndex = arr.slice(i + 1).findIndex(item => typeof item === 'string'); // 计算原数组中结束切片的绝对索引 const endIndex = nextTitleRelativeIndex === -1 ? undefined : i + 1 + nextTitleRelativeIndex; // 提取当前标题对应的所有对象 const objects = arr.slice(i + 1, endIndex); // 将标题和对象存入结果数组 acc.push({ title: curr, content: objects }); console.log({ title: curr, objects }); } return acc; }, []); console.log('最终结果:', result);
效果说明
修正后每个标题都能正确提取到对应的对象数组:
- "string 1"对应5个对象
- "string 2"对应4个对象
- "string 3"对应7个对象
内容的提问来源于stack exchange,提问作者Echo
相关产品推荐
相关产品推荐

