I have a multi-dimensional array of objects which contain suggested users. Again each suggested user has some suggested users and so on.
In the application I'm building I select a user (let's call him 'Steve') and would like to receive a certain amount of users connected to that user (by fetching the suggestions). The data is all there, I just need to find a meaningful way to iterate this.
To simplify I have built an array with some sample data where each user has two suggested users:
// Suggested users of my initially selected user (Steve)
let suggested_users_based_on_steve = [
{
name: 'A',
suggested: [
{
name: 'A1',
suggested: [
{ name: 'A1A1' },
{ name: 'A1A2' }
]
},
{
name: 'A2',
suggested: [
{ name: 'A2A1' },
{ name: 'A2A2' }
]
}
]
},
{
name: 'B',
suggested: [
{
name: 'B1',
suggested: [
{ name: 'B1B1' },
{ name: 'B1B2' }
]
},
{
name: 'B2',
suggested: [
{ name: 'B2B1' },
{ name: 'B2B2' }
]
}
]
}
];
Please note that the amount of suggested users is not fixed. Every user can have an unlimited amount of suggested users. Also, it's important iterate from layer to layer to get the 'best' and most connected results / users. The initial user is more connected to A and B than to A1A1 and A1A2.
I'm struggling with finding the right combination of nested for...of loops. Is there any recommended way on doing this?
Thank you in advance!
let suggested_users_based_on_steve = [
{
name: 'A',
suggested: [
{
name: 'A1',
suggested: [
{ name: 'A1A1' },
{ name: 'A1A2' }
]
},
{
name: 'A2',
suggested: [
{ name: 'A2A1' },
{ name: 'A2A2' }
]
}
]
},
{
name: 'B',
suggested: [
{
name: 'B1',
suggested: [
{ name: 'B1B1' },
{ name: 'B1B2' }
]
},
{
name: 'B2',
suggested: [
{ name: 'B2B1' },
{ name: 'B2B2' }
]
}
]
}
];
function test(arr, result = []) {
for (let user of arr.values()) {
result.push(user);
if (result.length === 7) return result;
}
var next = arr.reduce(function (all, user) {
return all.concat(user.suggested || []);
}, []);
if (next.length === 0) return result;
return test(next, result);
}
test(suggested_users_based_on_steve);