$(document).ready(function() {
const header = ["Info", "Info", "Info", "Info", "Sum1", "Sum2", "Info", "Sum3", "Info", "Info", "Sum4"];
const needles = ["Sum1", "Sum2", "Sum3", "Sum4"];
const spans = []; // new array
let cursor = 0; // cursor
spans[cursor] = {
text: '',
colspan: 0
};
for (let i = 0; i < header.length; i++) {
if (!needles.includes(header[i])) { // if not included, ++colspan
spans[cursor].colspan++;
} else {
if (i !== 0) cursor++; // only needed when we have a needle
// in the first header element
// here I create the new objects
// with the text Sum1, Sum2, etc
// and colspan=1
spans[cursor] = {};
spans[cursor].text = header[i];
spans[cursor].colspan = 1;
if (i === header.length - 1) continue; // if I am at the end
// of the header array,
// skip the next block
// if the next element in the header array is not included
// in needles, I already create a new element with
// colspan = 0 for the next loop.
// If the next element is also in needles it's not necessary
// as it will be catched by else{} block in the next loop
if (!needles.includes(header[i + 1])) {
cursor++;
spans[cursor] = {};
spans[cursor].text = '';
spans[cursor].colspan = 0;
}
}
}
console.log(spans);
for (const span of spans) {
$('#testTable tfoot tr').append(`<th colspan="${span.colspan}">${span.text}</th>`);
}
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="testTable" class="table table-bordered">
<thead>
<tr>
<th>Info</th>
<th>Info</th>
<th>Info</th>
<th>Info</th>
<th>Sum</th>
<th>Sum</th>
<th>Info</th>
<th>Sum</th>
<th>Info</th>
<th>Info</th>
<th>Sum</th>
</tr>
</thead>
<tbody>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>23</td>
<td>2</td>
<td>Text</td>
<td>245</td>
<td>Text</td>
<td>Text</td>
<td>4</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>23</td>
<td>2</td>
<td>Text</td>
<td>245</td>
<td>Text</td>
<td>Text</td>
<td>4</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>23</td>
<td>2</td>
<td>Text</td>
<td>245</td>
<td>Text</td>
<td>Text</td>
<td>4</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>Text</td>
<td>23</td>
<td>2</td>
<td>Text</td>
<td>245</td>
<td>Text</td>
<td>Text</td>
<td>4</td>
</tr>
</tbody>
<tfoot>
<tr>
</tr>
</tfoot>
</table>