Public
Edited
Dec 11, 2023
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
formatTable(cars, { header: ["awfes", 2, 3, 4, 5, 6, 7, 8] })
Insert cell
function formatTable(
data,
{
formatColumns = {},
colorScheme = d3.schemeRdYlGn[3],
columns = data.length != 0 ? Object.keys(data[0]) : [],
header = Object.keys(data[0]),

//Table CSS Properties
tableCSS = {
"overflow-x": "auto",
display: "block",
"min-width": "100%",
height: "100%",
"max-height": "240px"
},
// Function to compute the comparison value
cmpValueFn = (d) => d
} = {}
) {
if (data.length === 0) {
return;
}
let formatCSS = (d) =>
d &&
JSON.stringify(d).slice(1, -1).replaceAll('"', "").replaceAll(",", ";");

let formatColsKeys = Object.keys(formatColumns);
data = data.map((d) =>
columns.reduce((prev, col) => {
prev[col] = d[col];
return prev;
}, {})
);

const table = d3
.select("body")
.append("table")
.property("style", formatCSS(tableCSS));

table
.append("thead")
.append("tr")
.attr("class", "header")

.selectAll("th")
.data(header)
.join((enter) => enter.append("th").text((d) => d));

table
.append("tbody")
.selectAll("tr")
.data(data)
.join((enter) => enter.append("tr"))
.attr("class", "row")

.selectAll("td")
.data((row) => {
let cmpValue_ = cmpValueFn(row);
return columns.map((col) => {
let res = {};
res["value"] = row[col];

res["cmpValue_"] = cmpValue_;

if (formatColsKeys.includes(col)) {
let { condition, trueFormatting, falseFormatting } =
formatColumns[col];
if (condition(res["cmpValue_"], row)) {
res["style"] = trueFormatting;
} else {
res["style"] = falseFormatting;
}
}
return res;
});
})
.join((enter) =>
enter
.append("td")
.text((d) => d.value)
.property("style", (d) => formatCSS(d.style))
);

return html`${table.node()}`;
}
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