V
V
Vladislav Byvshev2015-10-22 21:32:12
JavaScript
Vladislav Byvshev, 2015-10-22 21:32:12

How to merge rows in an HTML table using JavaScript?

Hello toaster dwellers!
Question for the JavaScript experts:
How to merge rows in an HTML table using JavaScript?
There is a table:

<table>
   <tr><td>Значение 1</td><td>Количество 1</td></tr>
   ...
   ...
   <tr><td>Значение 1</td><td>Количество 2</td></tr>
   ...
   ...
</table>

Task:
merge table rows with cell "Value 1" and sum in the resulting row "Quantity 1" and "Quantity 2"
Result:
<table>
  ...
  ...
  ...
  ...
  <tr><td>Значение 1</td><td>Количество (1+2)</td></tr>
</table>

-----------------------------------------
Prompt the function to implement this operation.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2015-10-22
@glk92

You can play around with rows and cells and get something like this

function groupRows(table) {
    var uniqueRows = {},
    removedRows = [];

    [].forEach.call(table.rows, function (row) {
        var key = row.cells[0].textContent,
            value = +row.cells[1].textContent.split(' ')[1],
            sum;

        if (key in uniqueRows) {
            sum = uniqueRows[key].value + value;
            uniqueRows[key].row.cells[1].textContent = 'Количество ' + sum;
            uniqueRows[key].value = sum;
            removedRows.push(row);
        } else {
            uniqueRows[key] = {
                row: row,
                value: value
            };
        }
    });

    [].forEach.call(removedRows, function (row) {
        table.tBodies[0].removeChild(row);
    });
}

Function example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question