# Algorithm to find all connected objects

I'm creating a webapplication in which I render multiple objects using Three.js. These objects are saved in a list and can be connected to each other (but don't have to be), and when they are, they are rendered next to each other.

The user can select an object in this list using the UI that I made.

An example of how the objects can be positioned is in the image below. When I select the most left object I want the whole chain to be rendered, but not the 'singular' objects that are in the same list.

I hope this is clear enough, if not I will gladly elaborate.

Now the problem that I'm having:

The (simplified) list can look like this:

  {
id: 1,
connectedObjects: [{ id: 2 }, { id: 5 }],
},
{
id: 2,
connectedObjects: [{ id: 1 }, { id: 3 }],
},
{
id: 3,
connectedObjects: [{ id: 2 }, { id: 4 }],
},
{
id: 4,
connectedObjects: [{ id: 3 }],
},
{
id: 5,
connectedObjects: [{ id: 1 }],
},
{
id: 6,
connectedObjects: [],
},
{
id: 7,
connectedObjects: [],
},
{
id: 8,
connectedObjects: [],
},
];


Now I want to write an algorithm that checks which objects are all in the same 'group' as the selected object. So the last three (6, 7, 8) will not be rendered.

This is in JavaScript but if someone points me in the right direction with some pseudocode or a general idea that would be great!

• It looks like you are trying to find the connected components in an undirected graph. Googling those terms should point you to the right direction. The keywords "BFS on graph" or "DFS on graph" could also be useful. Commented Aug 10, 2020 at 11:34
• There is Disjoint-set datastructure, which allows you to construct the connected components and check membership efficiently.
– plop
Commented Aug 10, 2020 at 13:53
• You haven't defined what a 'singular' object is.
– D.W.
Commented Aug 10, 2020 at 18:19
• It may help to add at least one 'singular' object to the sketch, too. Commented Aug 11, 2020 at 2:29