/    Sign up×
Community /Pin to ProfileBookmark

How to return top parent from a given array ?

>

quote

The function should return the name of top parent when the person has one and null when he does not have a parent at all. I have made the code below but it seems that code prints the name of the person even when he doesnt have a parent instead of printing null :
“` code “

<script type=”text/javascript”>

var people = new Array();
people.push({name: “edd”, id : 1, parentId:null });
people.push({name: “jay”, id : 2, parentId:3});
people.push({name: “elen”, id : 3, parentId: 4});
people.push({name: “john”, id :4, parentId: null});
people.push({name: “bety”, id :5, parentId: null});

function findParent (people, Id){
debugger;
var ind = 0;
for (var i = 0; i < people.length; i++){
if (people[i].id == Id) {
console.log(people[i].id)
if (people[i].parentId != null) {
ind++;
return findParent(people, people[i].parentId);
}
else {
if (ind=0){
return null;

}else {
return people[i].name;

}

}
}
}
return “Id not found”;

}
alert(findParent(people,1));
</script>
</body>
</html>

“` code “

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@daveyerwinJun 03.2021 — @Developeralb#1632460

``<i>
</i>&lt;script type="text/javascript"&gt;

var people = new Array();
people.push({name: "edd", id : 1, parentId:null });
people.push({name: "jay", id : 2, parentId:3});
people.push({name: "elen", id : 3, parentId: 4});
people.push({name: "john", id :4, parentId: null});
people.push({name: "bety", id :5, parentId: null});


function findParent (people, id){
'use strict';
var ret = "person not found";
var person,name;

for (let i=0;i&lt;people.length;i++){
if (people[i].id === id) person = people[i];
}

if(person){
name = person.name;
ret = name + " has no parent";
if(person.parentId){
for (let i=0;i&lt;people.length;i++){
if (people[i].id === person.parentId){
ret = name + "'s parent is " + people[i].name;
}
}
}
}
return ret;
}
alert(findParent(people,15));
alert(findParent(people,1));
alert(findParent(people,2));
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;<i>
</i>
``
×

Success!

Help @Developeralb spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...