finding total amount of an html table in javascript per row

There are a few ways you can calculate the total of an HTML table in Javascript. You can use the built-in `Array.prototype.reduce()` function to iterate through each row and add the values in the columns together to get your total. Using the `Array.prototype.reduce()` function:

const table = document.getElementById('myTable');
const total = Array.from(table.rows).reduce((total, row) => {
  const num = row.querySelectorAll('td')[1].textContent;
  return total += parseInt(num);
}, 0);
console.log(total);

In the example above, `table` is the variable that holds the reference to your table element, and `total` is the variable that stores the total value. The `Array.from` function creates an array from the table rows. We then use `reduce` to iterate through each row and find the value in the second column, which we parse to `int` because it's a string value. We then add it to the total and return it. Another way to calculate the total is to create a for loop to iterate through each row and sum the values. Using a for loop:

const table = document.getElementById('myTable');
let total = 0;
for (let i = 0; i < table.rows.length; i++) {
  let num = table.rows[i].querySelectorAll('td')[1].textContent;
  total += parseInt(num);
}
console.log(total);

In the example above, `table` is the variable that holds the reference to your table element, `total` is the variable that stores the total value and `num` is the variable that holds the number value of the second column per row. We then parse the `num` to `int` because it's a string value, and add it to the total. Both of these methods will give you the same result, but depending on your situation, you may find one way more suitable than the other. I hope this helps!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe