Public
Edited
Mar 24, 2023
Paused
Insert cell
Insert cell
// splits an array into two arrays
function split(arr, index) {
return [arr.slice(0, index), arr.slice(index)];
}
Insert cell
// splits an array at the first element `predicate(e)` returns true for
function splitAt(arr, predicate) {
const index = arr.findIndex(predicate);
if (index == -1) return split(arr, arr.length);
return split(arr, index);
}
Insert cell
Insert cell
nodes = [1, 1, 3, 2, 1, 1, 2, 3, 1, 2];
Insert cell
// in this example the sequence [3, 2] starts a "section"
splitAt(nodes, (node, index, src) => {
return (node == 2) && (src[index - 1] == 3);
});
Insert cell
Insert cell
otherNodes = [
'blockquote', 'p', 'p',
'h2', 'blockquote', 'p', 'p', 'p',
'h2', 'blockquote', 'p', 'p', 'p',
];
Insert cell
isTitleNode = (node) => node == 'h2';
Insert cell
function sectionReducer(prev, cur) {
// when we encounter a title, start a new array
if (isTitleNode(cur)) {
prev.push([cur]);
} else {
// otherwise push the current node into the previous array
prev.at(-1).push(cur);
}
return prev;
}
Insert cell
otherNodes.reduce(
sectionReducer,
[[]] // start with array containing an empty array since we're returning an array of arrays
);
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