Published
Edited
Sep 26, 2022
Insert cell
Insert cell
viewof button = Inputs.button("Click me")
Insert cell
Insert cell
<ul id="root"></ul>
Insert cell
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
Insert cell
function redraw() {
const d = createData()

// data is either a list or a function to extract a list from the parent
function fillList(parents, data) {
const lis = parents.selectChildren("li")
.data(data)
.join("li")
.text(d => d.val)

console.log(lis)

// for every li that has children also append an "ul" element
// append, insert, and select propagate that data from the parent to the child
// this means that the ul elements have the same data as their parent li elements
const subUls = lis.filter(d => d.children)
.append("ul")


// if we have at least added one "ul" element, fill them
if(subUls.size() > 0) {
// call this method again recursivly
// to get the data for our li-elements, we extract the children from the ul elements
subUls.call(fillList, d => d.children)
// same:
// fillList(subUls, d => children)
}
}

const root = d3.select("#root")
fillList(root, d)
}
Insert cell
function createData() {
const n = getRandomInt(5) + 1
const data = []
for(let i = 0; i < n; i++) {
const d = { val: getRandomInt(250) + 1, key : "Key" + i}
if(Math.random() > 0.75) {
d.children = createData()
}
data.push(d)
}
return data
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more