你好@poppo8989:欢迎来到 Stack Overflow。
建议:如果您可以控制问题中呈现的数据,则可以考虑将其存储在更能代表关系的结构中。
否则,以下是解决您问题的方法:
Explore code in TypeScript Playground
type Person = {
name: string;
parent: string;
};
type RelationshipData = {
child?: Person;
parent?: Person;
};
function getRelationships (people: Person[], person: Person): RelationshipData {
return {
child: people.find(p => p.parent === person.name),
parent: people.find(p => p.name === person.parent),
};
}
function getSortedPeople (people: Person[]): Person[] {
const sorted: Person[] = [];
const copy = [...people];
while (copy.length > 0) {
let person: Person | undefined = copy[0];
let done = false;
// set person to furthest ancestor
while (person && !done) {
const {parent} = getRelationships(copy, person);
if (parent) person = parent;
else done = true;
}
// remove from copy array and add to sorted array, repeatedly for each child
while (person) {
copy.splice(copy.indexOf(person), 1);
sorted.push(person);
person = getRelationships(copy, person).child;
}
}
return sorted;
}
function main () {
const people: Person[] = [
{name: 'Bob', parent: 'Linda'},
{name: 'Charlie', parent: 'Gregory'},
{name: 'Linda', parent: 'Stacy'},
{name: 'Andrew', parent: 'Gabriel'},
{name: 'Gregory', parent: 'Thomas'},
];
const sorted = getSortedPeople(people);
console.log(sorted); //=> Linda, Bob, Gregory, Charlie, Andrew
}
main();