Public
Edited
Nov 14, 2023
Insert cell
Insert cell
data = {
return {
name: "John",
children: [
{
name: "Jim",
children: []
},
{
name: "Zoe",
children: [
{ name: "Kyle", children: [] },
{ name: "Sophia", children: [] }
]
}
]
};
}
Insert cell
function getChildren(parent, child_list = []) {
// Break out clause
if (parent.children.length === 0) {
return child_list;
}
// Recursion
parent.children.forEach((d) => {
child_list.push(d.name);
getChildren(d, child_list);
});

return child_list;
}
Insert cell
getChildren(data)
Insert cell
function getChildrenFlatMap(tree) {
// Using flatmap will remove any empty arrays
const nestedNames = tree.children.flatMap((d) => getChildrenFlatMap(d));
const childNames = tree.children.map((d) => d.name);
return [...childNames, ...nestedNames];
}
Insert cell
getChildrenFlatMap(data)
Insert cell
d3.range(0, 4).map((d) => Array.from({ length: d }, (d, i) => i))
Insert cell
d3.range(0, 4).flatMap((d) => Array.from({ length: d }, (d, i) => i))
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