Published
Edited
Jul 30, 2022
1 fork
Importers
16 stars
Insert cell
Insert cell
Insert cell
Insert cell
// use as a viewof (single table) on markdown or html markup
viewof c = tableView(md`| date | name | value |
|---
| 22.01 | Julie | $3 |
| 24.01 | Ahmad | $13 |
| 25.01 | Baruch | $2 |
`)
Insert cell
c
Insert cell
Insert cell
a = html`<table><thead><tr><th>date</th><th>name</th><th>value</th></tr></thead><tbody><tr><td>22.01</td><td>Julie</td><td>$3</td></tr><tr><td>24.01</td><td>Ahmad</td><td>$13</td></tr><tr><td>25.01</td><td>Baruch</td><td>$2</td></tr></tbody></table>`
Insert cell
// extract one table
tableExtractor(a)
Insert cell
Insert cell
// extract several tables
tableExtractor(b, true)
Insert cell
// extract all the tables in the document
(a, b, tableExtractor(d3.selectAll("table"), true))
Insert cell
Insert cell
fetch(CORS_PROXY + "https://en.wikipedia.org/wiki/List_of_sandwiches")
.then((resp) => resp.text())
.then((html) => d3.create("div").html(html))
.then(tableExtractor)
Insert cell
Insert cell
tableExtractor = (root, multiple = false) => {
const T = [];
if (!root || !root.selectAll) root = d3.select(root);
const tables = root
.filter(function() {
return this.nodeName === "TABLE";
})
.size()
? root.nodes()
: root.selectAll("table");

for (const table of tables) {
const keys = [],
rows = [];
for (const th of d3.select(table).selectAll("th")) {
keys.push(th.innerText.trim());
}
for (const tr of d3
.select(table)
.select("tbody")
.selectAll("tr")) {
// if we haven't found a thead, number keys
if (keys.length === 0) {
d3.select(tr)
.selectAll("td")
.each((_, i) => keys.push(i));
}
const row = {};
let i = 0;
for (const td of d3.select(tr).selectAll("td")) {
const k = keys[i++];
if (k) row[k] = td.innerText.trim();
}
rows.push(row);
}
rows.columns = keys;
if (keys.length) T.push(rows);
}
return multiple ? T : T[0];
}
Insert cell
tableView = (element, multiple) => {
return Object.assign(element, { value: tableExtractor(element, multiple) });
}
Insert cell
d3 = require("d3-selection@2")
Insert cell
// import { CORS_PROXY } from "@fil/cors-proxy"
CORS_PROXY = "https://cors-anywhere.herokuapp.com/"
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