EDIT: If you want to have a different order, you could keep the order itself in a seperate array and process with that array as in this fiddle. Also to have the sum, select all the Inventory Amount fields from the individual array using Array.map and populate sum using some logic, I used Array.reuce for that.
Working Fiddle
// Array to keep the order of itration
const order = [0, 2, 1, 3, 4];
let products = [
["product1", "Small Widget", "159753", 33, 22],
["product2", "Medium Widget", "258456", 55, 44],
["product3", "Large Widget", "753951", 77, 88],
["product4", "Not a Widget", "852654", 11, 2],
["product5", "Could be a Widget", "654456", 99, 6],
["product6", "Ultimate Widget", "321456", 111, 66],
["product7", "Jumbo Small Medium Widget", "987456", 88, 11]
];
//first create the table
function generateTableHead(table, data) {
let thead = table.createTHead();
let row = thead.insertRow();
for (let key of dataorder) {
let th = document.createElement("th");
let text = document.createTextNode(keydata[key]);
th.appendChild(text);
row.appendChild(th);
}
}
function generateTable(table, data) {
for (let element of data) {
let row = table.insertRow();
for (key in element) {
let cell = row.insertCell();
const textContent = keyorder[key] === '3'3 ? '$' + element[key]element[order[key]] : element[key];element[order[key]];
let text = document.createTextNode(textContent);
cell.appendChild(text);
if (keyorder[key] === "4"4 && element[key]element[order[key]] < 20) {
cell.style.background = "grey";
}
}
}
}
function generateTableFooter(table) {
let row = table.insertRow();
// My summation logic
// Select the Inventory Amount from each array in products, which is the 5th element of array
// `map` will generate an array with all Inventory Amount [22, 44, 88, 2, 6, 66, 11]
// `reduce` will loop through this array and will find the sum
const total = products.map((product) => product[4]).reduce((sum, curr) => {
sum += curr;
return sum;
}, 0);
for (let key of order) {
let cell = row.insertCell();
const textContent = order[key] === 4 ? total : '';
let text = document.createTextNode(textContent);
cell.appendChild(text);
}
}
let table = document.querySelector("table");
const header = [ "Product["Product Name", "Product Description", "Product ID", "Price", "Inventory Amount"];
generateTable(table, products);
generateTableHead(table, header);
generateTableFooter(table);
<table id="test">
<id="test"></table>