Published
Edited
Mar 26, 2020
Importers
Insert cell
md`# Table`
Insert cell
_ = require('lodash')
Insert cell
table = {
return (index, columns, groups, cb) => {
const element = html`
<div style="overflow: auto; overflow-x: scroll; width: 800px; max-height: 300px;">
<table>
<thead>
<tr style="background: white;">
<th style="min-width: 200px; height: 44px; position: sticky; left: 0; top: 0; background: white; z-index: 2;">${index[0].name}</th>
${index.length > 1 ? html`<th style="position: sticky; top: 0; left: 200px; background: white; z-index: 2;">${index[1].name}</th>` : ''}
${columns.map(({name}) => html`<th style="padding: 12px; position: sticky; top: 0; height: 44px; background: white;">${name}</th>`)}
</tr>
</thead>
<tbody>
${groups.flatMap((members, groupNum) => members.map((datum, rowNum) => html`
<tr>
${rowNum === 0 ? html`<td style="min-width: 200px; position: sticky; left: 0; background: white;">${datum[index[0].key]}</td>` : html`<td style="min-width: 200px; background: white; left: 0; position: sticky;" />`}
${index.length > 1 ? html`<td style="position: sticky; left: 200px; background: white;">${datum[index[1].key]}</td>` : ''}
${columns.map(({key, format}) =>
html`<td
data-cell="${[...index.map(({key}) => datum[key]), key].join('<SEP>')}"
style="padding: 0 12px;"
>${(format && datum[key]) ? format(datum[key]) : (datum[key] || '')}</td>`
)}
</tr>
`))}
</tbody>
</table>
</div>
`
element.addEventListener('click', evt => {
if (evt.target.dataset.cell) {
cb(_.zipObject([...index.map(({key}) => key), 'column'], evt.target.dataset.cell.split('<SEP>')))
}
})
return element
}
}
Insert cell
{
const data = [
[
{state: 'California', city: 'San Francisco', population: 884363, costOfLiving: 2, unemployment: 0.019},
{state: 'California', city: 'Los Angeles', population: 4e6, costOfLiving: 1.5, unemployment: 0.04},
],
[
{state: 'Connecticut', city: 'Greenwich', population: 62610, costOfLiving: null, unemployment: 0.025},
],
]
return table(
[{name: 'State', key: 'state'}, {name: 'City', key: 'city'}],
[{name: 'Population', key: 'population'}, {name: 'Cost of Living', key: 'costOfLiving'}, {name: 'Unemployment', key: 'unemployment'}],
data,
datapoint => console.log(datapoint)
)
}
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