Skip to main content

Adjacency list

JointJS+ provides a toAdjacencyList plugin that enables the ability to convert a graph to an adjacency list.

Installation

Access toAdjacencyList via the graphUtils namespace.

import { dia, shapes, graphUtils } from '@joint/plus';

const graph = new dia.Graph({}, { cellNamespace: shapes });

const a = new shapes.standard.Ellipse({ id: 'a' });
const b = new shapes.standard.Ellipse({ id: 'b' });
const c = new shapes.standard.Ellipse({ id: 'c' });

const ab = new shapes.standard.Link({
id: `a-b`,
source: { id: 'a' },
target: { id: 'b' },
});

const bc = new shapes.standard.Link({
id: `b-c`,
source: { id: 'b' },
target: { id: 'c' },
});

const indirectLink = new shapes.standard.Link({
id: `indirectLink`,
source: { id: 'a' },
target: { id: 'b-c' },
});

graph.addCells(a, b, c, ab, bc, indirectLink);

graphUtils.toAdjacencyList(graph);
// Returns an object:
// {
// "a": ["b", "c"],
// "b": ["c"],
// "c": []
// }
There is also a UMD version available

Include joint.graphUtils.js in your HTML:

index.html
<script src="joint.js"></script>
<script src="joint.graphUtils.js"></script>

Access toAdjacencyList through the joint.graphUtils namespace:

index.js
const graph = new joint.dia.Graph({}, { cellNamespace: joint.shapes });

const a = new joint.shapes.standard.Ellipse({ id: 'a' });
const b = new joint.shapes.standard.Ellipse({ id: 'b' });
const c = new joint.shapes.standard.Ellipse({ id: 'c' });

const ab = new joint.shapes.standard.Link({
id: `a-b`,
source: { id: 'a' },
target: { id: 'b' },
});

const bc = new joint.shapes.standard.Link({
id: `b-c`,
source: { id: 'b' },
target: { id: 'c' },
});

const indirectLink = new joint.shapes.standard.Link({
id: `indirectLink`,
source: { id: 'a' },
target: { id: 'b-c' },
});

graph.addCells(a, b, c, ab, bc, indirectLink);

joint.graphUtils.toAdjacencyList(graph);
// Returns an object:
// {
// "a": ["b", "c"],
// "b": ["c"],
// "c": []
// }

How does toAdjacencyList work?

It converts a graph to an adjacency list. The method returns an object with element ids as properties, and an array of connected element ids as values (the array includes indirect connections i.e. the path between connected elements includes a link-link connection).

Stay in the know

Be where thousands of diagramming enthusiasts meet

Star us on GitHub