I have got a table with redundant data in cells. [Left table]
I need to join them into one cell. [Right table]
Structure of table:
<table>
<tr>
<td class="bold">Value1:</td>
<td class="green">A</td>
<td class="green">A</td>
<td class="green">A</td>
<td> </td>
<td> </td>
<td> </td>
<td class="green">B</td>
<td class="green">B</td>
</tr>
<tr>
<td class="bold">Value2:</td>
<td> </td>
<td> </td>
<td class="green">C</td>
<td class="green">C</td>
<td> </td>
<td> </td>
<td class="green">D</td>
<td> </td>
</tr>
</table>
I am able to hide redundant cell, but I need to set colspan somehow.
$(document).ready(function () {
var all = $('.green');
var seen = {};
all.each(function () {
var txt = $(this).text();
if (seen[txt]) {
$(this).hide();
}
else {
seen[txt] = true;
}
});
});
$(document).ready(function() {
var all = $('.green');
var first;
var prev = undefined;
var colspan = 1;
var setColspan = function() {
first.attr('colspan', colspan);
colspan = 1;
}
all.each(function() {
var txt = $(this).text();
if (prev === txt) {
colspan += 1;
$(this).remove();
} else {
// doesnt match, set colspan on first and reset colspan counter
if (colspan > 1) {
setColspan();
}
first = $(this);
prev = txt;
}
});
if (colspan > 1) {
setColspan();
}
});
td {
border: 1px solid;
text-align: center;
min-width: 25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<table>
<tr>
<td class="bold">Value1:</td>
<td class="green">A</td>
<td class="green">A</td>
<td class="green">A</td>
<td> </td>
<td> </td>
<td> </td>
<td class="green">B</td>
<td class="green">B</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td class="bold">Value2:</td>
<td> </td>
<td> </td>
<td class="green">C</td>
<td class="green">C</td>
<td> </td>
<td> </td>
<td class="green">D</td>
<td> </td>
</tr>
</table>
Think it does what you want, checks for consecutive blocks of matching column values, if it finds a match, it removes it, when it doesnt find a match and colspan is large enough it sets the colspan on the first in the list and then resets. it doesnt work if you have consecutive values that span end of one row and into the beginning of the next. would want to do it row by row if that is the case
updated above with edge case if last set of columns are consecutive as well. it wouldnt set the colspan in that case then.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With