I am working with an array of objects that contain information about different projects. Each project has a unique ID and two arrays, one containing the IDs of projects that will happen before it, and another with the IDs of projects that will follow. Here's an example:
let projects = [];
projects[0] = {
id: "ID_123",
before: [],
after: ["ID_523"],
}
projects[1] = {
id: "ID_523",
before: ["ID_123"],
after: ["ID_523","ID_827"],
}
My goal is to identify all projects that depend on each other and group them together in subgroups. I approach this by iterating through the array starting from projects with no predecessors and then sequentially adding projects that follow into the same subgroup until there are no more subsequent projects. Here is my algorithm:
let subgroup = 0;
// loop through project array
for (let i=0; i<projects.length; i++) {
let next = projects[i]; // next contains the next project in the row
// find projects that have no projects happening before
if ((!next.hasOwnProperty('subgroup')) && (next.before.length == 0)) {
// do this as long as the next project has projects happening after
while (next.after.length > 0) {
// find the array-key of the first project happening afterwards
let key;
for (let n=0; n<projects.length; n++) {
if (projects[n].id == next.after[0]) {
key = n;
break;
}
}
// set the subgroup of the project with the key from above
projects[key].subgroup = subgroup;
// set the next project
next = projects[key];
}
subgroup++;
}
}
Unfortunately, my algorithm does not assign subgroups to some projects as intended. Despite spending days trying to debug it, I cannot seem to locate the error.
If anyone can help me identify what I'm doing wrong, I would greatly appreciate it. Thank you in advance!