<head>
<style>
table {
border: 1px solid black;
border-collapse: collapse;
}
td {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="mytable"></table>
<script>
const data = [
{id:"1", name: "1", fid:""},
{id:"2", name: "2", fid:"1"},
{id:"3", name: "3", fid:"3"},
{id:"4", name: "4", fid:"4"},
{id:"5", name: "5", fid:"1"},
{id:"6", name: "6", fid:""},
{id:"7", name: "7", fid:"5"},
{id:"8", name: "8", fid:""},
{id:"9", name: "9", fid:"3"},
{id:"10", name: "10", fid:"1"},
{id:"11", name: "11", fid:""},
{id:"12", name: "12", fid:"5"}
];
function groupe (data) {
const groupedata = [];
for (const {id, name, fid} of data) {
if (fid === "") {
groupedata.push({rows:[{id, name}], fid});
} else {
const row = groupedata.find(row => row.fid === fid)
if (!row) {
groupedata.push({rows:[{id, name}], fid});
} else {
row.rows.push({id, name})
}
}
}
return groupedata;
}
function createtable (table, groupedata) {
const thead = document.createElement('thead')
thead.innerHTML = '<tr><th>id</th><th>name</th><th>fid</th></tr>';
table.append(thead);
const tbody = document.createElement('tbody');
for (const {rows, fid} of groupedata) {
for (let i = 0; i<rows.length; i++) {
const row = document.createElement('tr');
const tdid = document.createElement('td');
const tdname = document.createElement('td');
tdid.textContent = rows[i].id;
tdname.textContent = rows[i].name;
row.append(tdid,tdname);
if (i === 0) {
const tdfid = document.createElement('td');
tdfid.textContent = fid;
tdfid.rowSpan = rows.length;
row.append (tdfid)
}
tbody.append (row);
}
}
table.append(tbody);
}
const groupedata = groupe(data);
createtable(document.getElementById('mytable'), groupedata);
</script>
<body>