gpt4 book ai didi

JavaScript:解决算法问题

转载 作者:行者123 更新时间:2023-11-29 20:42:53 25 4
gpt4 key购买 nike

今天我在做一个问题,它的状态如下:

问题:

  • 输入:[{..}, {..}, ..]对象数组;
  • 每个对象都有 {"id": required, "children": []}
  • 根据"id" and "children",对象具有父子关系 Prop
  • 输出:[{..}, {..}, ..]树状数组(层次结构)顺序:多级


输入:

[{
"id": 1,
"name": "Earth",
"children": [2, 3]
}, {
"id": 2,
"name": "Asia",
"children": []
}, {
"id": 3,
"name": "Europe",
"children": [4]
}, {
"id": 4,
"name": "Germany",
"children": [5]
}, {
"id": 5,
"name": "Hamburg",
"children": []
}]

输出

[{
"id": 1,
"name": "Earth",
"children": [{
"id": 2,
"name": "Asia",
"children": []
}, {
"id": 3,
"name": "Europe",
"children": [{
"id": 4,
"name": "Germany",
"children": [{
"id": 5,
"name": "Hamburg",
"children": []
}]
}]
}]
}]

我的方法

我决定通过遍历数组中的每个元素并递归查找对象并将其附加到 children 来解决这个问题 每个元素。

So just to start with, I decided to have only First level children appended their respective parents. And my code is following.

var posts = [{"id":1,"name":"Earth","children":[2,3]},{"id":2,"name":"Asia","children":[]},{"id":3,"name":"Europe","children":[4]},{"id":4,"name":"Germany","children":[5]},{"id":5,"name":"Hamburg","children":[]}]

function getElementById (id, posts) {
for(var i =0; i< posts.length; i++){
if(posts[i].id === id){
var found = posts[i];
///// FUN here -> //// posts.splice(i, 1);
return found;
}
}
}

function refactorChildren(element, posts) {
if(!element.children || element.children.length === 0) {
return element;
}

var children = [];
for(var i = 0; i < element.children.length; i++){
var childElement = getElementById(element.children[i], posts);
children.push(childElement);
}
element.children = children;

return element;
}

function iterate(posts) {
var newPosts = [];
var des = [...posts]
for(var i = 0; i < des.length; i++){
var childedElement = refactorChildren(des[i], des);
newPosts.push(childedElement);
}

return newPosts;
}


var filtered = iterate(posts);
console.log(JSON.stringify(filtered))

Surprisingly above code Solves the ACTUAL PROBLEM (except a lil bit of more work)

我的预期结果应如下所示: 只有第一级 child

的对象数组
[{
"id": 1,
"name": "Earth",
"children": [{
"id": 2,
"name": "Asia",
"children": []
}, {
"id": 3,
"name": "Europe",
"children": [4]
}]
}, {
"id": 4,
"name": "Germany",
"children": [{
"id": 5,
"name": "Hamburg",
"children": []
}]
}]

如果我取消对 ///// FUN here -> //// 的注释,我确实会得到上述结果线。这是在移动中删除迭代对象。

所以我的问题是

我想知道 - 怎么做到的?所有对象都通过该代码正确附加到它们各自的父对象吗?我的下一步是添加对函数 refactorChildren(with-childElement) 的递归调用。 .

怎么做到的,就是加了posts.splice(i, 1);从代码中得到了我的预期结果?

请帮助我理解,我只是不知道“怎么做”才能继续。

谢谢

最佳答案

在遍历对象时,您递归地对其所有子对象调用一个函数并从数组中删除对象:

 [
{ id: 1, children: [2], }, // < iterator
{ id: 2, children: [] }, // < gets spliced out recursively
]

但是,如果子项位于其父项之前的数组中,则这将不起作用,因为您在访问父项之前将子项复制到另一个数组中。

关于JavaScript:解决算法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55079979/

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