Below is an instruction that describes a task. Write a response that appropriately completes the request
Please write a function called sumTable that accepts a query selector for an HTML table. The function should take a query selector string as a parameter. sumTable should loop through the columns of the table adding all the cells in each column if they are numbers (ignore cells that do not contain a number.) It should then add a row to the table containing the the sum of each column.
The function must be javascript.
function sumTable(table) {
// Get the number of rows and columns in the table
const rows = table.rows.length;
const cols = table.rows[0].cells.length;
// Initialize an array to store the sums of each column
const sums = new Array(cols).fill(0);
// Loop through each row and column, adding the value to the corresponding sum
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const cell = table.rows[i].cells[j];
const value = parseFloat(cell.innerText);
if (!isNaN(value)) {
sums[j] += value;
}
}
}
// Add a new row to the table containing the sums
const newRow = table.insertRow();
for (let j = 0; j < cols; j++) {
const cell = newRow.insertCell();
cell.innerText = sums[j];
}
}
This function takes a table element as input and adds a new row to the end of the table containing the sum of each column. It first gets the number of rows and columns in the table, and initializes an array to store the sums of each column. It then loops through each row and column, adding the value to the corresponding sum if it is a number. Finally, it adds a new row to the table containing the sums.
Note that this implementation assumes that the table has a header row, and that the first row of data starts at the second row. If your table has a different structure, you may need to adjust the code accordingly.
Question1.md and Question2.md are questions that I asked the LLM, I then put together sum_table.html combining the two and ran it to get the screenshot above.