Public
Edited
Apr 9, 2023
Paused
Insert cell
Insert cell
Insert cell
{
// create file input elements for the two files
const fileInput1 = html`<input type="file" />`;
const fileInput2 = html`<input type="file" />`;

// create empty HTML tables for the two files
const table1 = html` <table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>`;
const table2 = table1.cloneNode(true);

// function to handle file load event and display stats in table
const handleFileLoad = (table) => async (event) => {
const file = event.target.files[0];
const reader = new FileReader();

// read the file contents as text
reader.readAsText(file);

// create a promise to wait for the file to load and parse
const fileLoaded = new Promise((resolve, reject) => {
reader.onload = () => {
const contents = reader.result;
const lines = contents.trim().split("\n");
const headers = lines[0].split(",");
const numColumns = headers.length;
const numRows = lines.length - 1;

// create a row for the number of rows
const numRowsRow = html`<tr>
<td>Number of rows:</td>
<td>${numRows}</td>
</tr>`;

// create a row for the number of columns
const numColsRow = html`<tr>
<td>Number of columns:</td>
<td>${numColumns}</td>
</tr>`;

// create a row for the column names
const headerRow = html`<tr>
<td>Column names:</td>
<td>${headers.map((h, i) => `${i}: ${h}`).join(", ")}</td>
</tr>`;

// add the rows to the table body
const tableBody = html`<tbody>
${numRowsRow}${numColsRow}${headerRow}
</tbody>`;

table.replaceChild(tableBody, table.lastChild);

// resolve the promise with the parsed data
resolve({ numRows, numColumns, headers });
};

reader.onerror = () => {
reject(reader.error);
};
});

// wait for the promise to resolve before displaying the results in the table
try {
const { numRows, numColumns, headers } = await fileLoaded;
console.log(
`File loaded: ${file.name}, Rows: ${numRows}, Columns: ${numColumns}, Headers: ${headers}`
);
} catch (err) {
console.error(err);
}
};

// add event listeners to the file input elements
fileInput1.addEventListener("change", handleFileLoad(table1));
fileInput2.addEventListener("change", handleFileLoad(table2));

// display the file input and table elements in the notebook
return html`${fileInput1} ${table1} ${fileInput2} ${table2}`;
}
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