Skip to content

Instantly share code, notes, and snippets.

@iosonosempreio
Last active June 12, 2018 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iosonosempreio/f628969aa68a1288c4794b7e7cd81d52 to your computer and use it in GitHub Desktop.
Save iosonosempreio/f628969aa68a1288c4794b7e7cd81d52 to your computer and use it in GitHub Desktop.
Create Network from table
// original data
let data = [];
// filter data arraybased on another array
// get the records that have a certain property
let filtered = data.work.filter(function(d) {
return selectedIDs.indexOf(d['property']) > -1;
})
nodes = [];
links = [];
filtered.forEach(function(d, i) {
// in some cases (i.e. letters) source could be undefined
if (d.hasOwnProperty('source id')) {
nodes.push({
id: d['source id'],
label: d['source label']
});
}
// in some cases (i.e. letters) target could be undefined
if (d.hasOwnProperty('target id')) {
nodes.push({
id: d['target id'],
label: d['target label']
});
}
// so check links
if (d.hasOwnProperty('source id') && d.hasOwnProperty('target id')) {
links.push({
id: d['source id'] + '-' + d['target id']
})
}
});
// remove duplicates, first nest, than map
nodes = d3.nest()
.key(function(d) { return d.id })
.entries(nodes)
nodes = nodes.map(function(d) {
return {
id: d.key,
label: d.values[0].label,
value: d.values.length
}
})
links = d3.nest()
.key(function(d) { return d.id })
.rollup(function(leaves) { return leaves.length; })
.entries(links)
links = links.map(function(d) {
return {
id: d.key,
source: nodes.filter(function(e) { return e.id == d.key.split('-')[0] })[0],
target: nodes.filter(function(e) { return e.id == d.key.split('-')[1] })[0],
value: d.value
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment