I have a deep array of objects like {id, followers}
where followers
repeat the pattern:
{
id: 0, followers: [{
id: 1, followers: [{
id: 11, followers: [{
id: 111, followers: [...]
}]
}]
}, {
id: 2, followers: [{
id: 21, followers: [{
id: 211, followers: [...]
}]
}]
}, {
id: 3, followers: [{
id: 31, followers: [...]
}]
}, ...]
}
I want to walk this tree and create a flattened array of type {id, depth}
I'm using the following recursive function:
function recurse(user, depth = 0, list = []) {
for (const { id } of user.followers) {
list.push({ id, depth });
}
for (const follower of user.followers) {
recurse(
user: follower,
depth: depth + 1,
list
);
}
return list;
}
It goes deeper and deeper into every branch before moving on, which results in something like
[
{ id: 0, depth: 0},
{ id: 1, depth: 1},
{ id: 11, depth: 2},
{ id: 111, depth: 3},
{ id: 1111, depth: 4},
{ id: 11111, depth: 5},
...
{ id: 2, depth: 1},
{ id: 21, depth: 2},
{ id: 211, depth: 3},
...
{ id: 3, depth: 1},
{ id: 31, depth: 2},
{ id: 311, depth: 3},
...
]
But I want this to automatically come out as sorted by depth, like this:
[
{ id: 0, depth: 0},
{ id: 1, depth: 1},
{ id: 2, depth: 1},
{ id: 3, depth: 1},
{ id: 4, depth: 1},
...
{ id: 11, depth: 2},
{ id: 12, depth: 2},
{ id: 13, depth: 2},
...
{ id: 111, depth: 3},
{ id: 211, depth: 3},
...
]
I want to go elements depth-wise, i.e. all elements from depth 0, then all elements from depth 1, and so on.
My implementation doesn't respect the depth order. It simply follows the branches as deep as they go first, then moves on to the next branch.
I know I can just sort it later, but other problems prevent me from doing that. Mainly I have duplicate items and I want to filter those out. And while filtering, I want to keep the items with lowest depth. My approach doesn't allow that because it doesn't go through all elements of lowest depth first.
How can I traverse this tree depth-wise instead of branch-wise?