In my current programming challenge, I am dealing with an array of objects that have two properties: target
and source
. Additionally, there is a designated starting source
to begin with.
The goal is to start from the starting source
and recursively find a target
from the given array
. Once a target
is found, it becomes the new source
and the process continues until the target value is undefined.
I am seeking an efficient way to achieve this task and would appreciate any concise code suggestions.
let result = new Array();
// input
const a = [
{ source: '2', target: '3' },
{ source: '1', target: '2' },
{ source: '3', target: '4' },
{ source: '4', target: '5' }
];
const startSource = '1';
result.push(startSource);
// recursive function
this.findTarget(startSource, a);
console.log(result);
Here is the recursive function I have implemented:
public findTarget(s: string, a: Sequence[]): any {
let obj = a.find(i => i.source === s);
if (obj) {
this.result.push(obj.target);
return this.findTarget(obj.target, a);
} else {
return;
}
}