gpt4 book ai didi

javascript - 将对象数组缩减为嵌套数组

转载 作者:行者123 更新时间:2023-11-30 09:14:41 24 4
gpt4 key购买 nike

我正在尝试将元素相互嵌套,但今天我脑袋放屁。

如果数组中的元素是 isParent: true,那么它将在现有数组中创建一个新数组,并且所有后续元素都将嵌套在该数组中。

到目前为止,这是我尝试过的:

//input [{},{},{},{isParent}, {}, {}, {isParent}, {}, {}]
//desired output [{}, {}, {}, [{}, {}, {}, [{}, {}, {}]]]

var nestInParent = elements => {
let ignoreIndexAfter = null;
return elements.reduce((acc, { component, isParent }, index) => {
if (isParent) {
let remaining = elements.slice(index + 1);
ignoreIndexAfter = index;
if (remaining.length > 0) {
return [...acc, [component, ...nestInParent(remaining)]];
} else {
return [...acc, [component]];
}
} else {
if(ignoreIndexAfter === null || index < ignoreIndexAfter){
return [...acc, component];
}
return acc;
}
}, []);
};
const isParent = true;
const input = [
{component:0},
{component:1},
{component:2},
{isParent, component:3},
{component:4},
{component:5},
{isParent, component:6},
{component:7},
{component:8}
];
const expected = [
0,
1,
2,
[
3,
4,
5,
[
6,
7,
8
]
]
];
const output = nestInParent(input);
console.log("input:", input);
console.log("output:", output);
console.log("passes?", JSON.stringify(output) === JSON.stringify(expected));
.as-console-wrapper { max-height: 100% !important; }

最佳答案

您也可以使用 reduce 方法和一个变量来跟踪是否找到具有 isParent 属性的元素。

const isParent = true;
const input = [{component:0},{component:1},{component:2},{isParent, component:3},{component:4},{component:5},{isParent, component:6},{component:7},{component:8}];

function nest(data) {
let nested = false;
return data.reduce((r, e, i) => {
if(!nested) {
if(e.isParent) {
const res = nest(data.slice(i + 1))
r.push([e.component, ...res])
nested = true;
} else {
r.push(e.component)
}
}
return r;
}, [])
}

const result = nest(input);
console.log(result)

也可以这样写

const isParent = true;
const input = [{ component: 0 }, { component: 1 }, { component: 2 }, { isParent, component: 3 }, { component: 4 }, { component: 5 },{ isParent, component: 6 }, { component: 7 }, { component: 8 }];

function nest(data, nested) {
return data.reduce((r, e, i) => {
if(!nested) {
if(e.isParent && i != 0) {
r.push(nest(data.slice(i)))
nested = true;
} else {
r.push(e.component)
}
}
return r;
}, [])
}

const result = nest(input);
console.log(result)

关于javascript - 将对象数组缩减为嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55950232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com