如何对数组进行切片,直到某个元素

How to slice an array up until a certain element

提问人:Echo 提问时间:9/6/2023 更新时间:9/6/2023 访问量:58

问:

我有一个包含字符串和对象的数组。字符串充当“标题”,而后面的对象是“内容”。出于虚拟化目的,它以这种方式排列。这是我到目前为止得到的

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
}, [])

我需要将当前迭代的标题和下一个标题之间的所有对象都放在该行中。(在示例中,“字符串 1”和“字符串 2”之间的对象等)

第一次和最后一次迭代按预期工作,变量包含从 到 的 5/7 个对象。但是,中间迭代不会生成所需的值,它会变成一个空数组。objectsfirstlastobjects

JavaScript 数组 切片

评论


答:

1赞 Ilja KO 9/6/2023 #1

你没有指定最终结果应该是什么,所以我为你挑选了两个:

数组数组,数组的第一个元素是标题:

const result = [];
test.forEach((s) => {
  if(typeof s === 'string') {
    result.push([]);
  }
  result[result.length - 1].push(s); // access error when the test data is not structured correctly
});

console.log(result); // [['string 1', { prop1: "string 1 obj first" }, ...],['string 2', ...], ...]

一个对象,其中键是标题,值是内容对象的数组:

const result = {};
let key = undefined;
test.forEach((s) => {
  if(typeof s === 'string') {
    key = s;
    result[key] = [];
  } else {
    result[key].push(s); // access error when the test data is not structured correctly
  }  
});

console.log(result); // {string 1: [{ prop1: "string 1 obj first" }, ...], string 2: [...], ...}

评论

0赞 Echo 9/8/2023
结果应该只是对象的数组。我做了一个不同的实现,但谢谢你的回答