Given an array 'featureList', the goal is to create a new array 'newArray' based on a specific ID. For example, for ID 5, the newArray would be ['MotherBoard','Antenna','Receiver'], where Receiver corresponds to the current ID, Antenna is from the parentID of Receiver, and MotherBoard is from the parentID of Antenna.
What recursive approach would be most effective in achieving this new array?
The current code provided below is not successfully producing the desired outcome.
const newArray: string[] = [];
for (const feature of featureList) {
if (feature.id === this.featureId) {
newArray.push(feature.name);
if (feature.parentFeatureId) {
for (const parentFeature of featureList) {
if (parentFeature.id === feature.parentFeatureId) {
newArray.push(parentFeature.name);
}
}
}
}
}
var featureList = [
{
"id": 1,
"name": "MotherBoard",
"projectId": 1,
"parentFeatureId": null
},
{
"id": 2,
"name": "Power Supply",
"projectId": 1,
"parentFeatureId": 1
},
{
"id": 3,
"name": "Antenna",
"projectId": 1,
"parentFeatureId": 1
},
{
"id": 4,
"name": "Transmitter",
"projectId": 1,
"parentFeatureId": 3
},
{
"id": 5,
"name": "Receiver",
"projectId": 1,
"parentFeatureId": 3
},
{
"id": 6,
"name": "Storage",
"projectId": 1,
"parentFeatureId": null
},
{
"id": 7,
"name": "Calibration State",
"projectId": 1,
"parentFeatureId": 6
},
{
"id": 8,
"name": "User Profile mgm",
"projectId": 1,
"parentFeatureId": 6
},
{
"id": 9,
"name": "HW State mgm",
"projectId": 1,
"parentFeatureId": 6
}
]