I want to extract the headers data and column data (not row data) from htmlan HTML table using javascriptJavaScript. Is
Is this a good approach of doing it?
and And how can iI simplify this using jqueryjQuery?
let table = document.getElementById('tab')
debugger
let headers = Array.from(table.rows[0].cells).map(x => x.innerText)
let columnData =
Array.from(table.rows).
slice(1, table.rows.length).
map(row =>Array.from(row.cells).map(x => x.innerText))
.reduce((acc,rowData)=>{
rowData.forEach((value,index)=>{
acc[index]= acc[index] || [ ]
acc[index].push(value) })
return acc },[])
console.log(headers)
console.log(columnData)
<table id="tab">
<tr>
<th>
Name
</th>
<th>
Age
</th>
<th>
Location
</th>
</tr>
<tr>
<th>
Jason
</th>
<th>
22
</th>
<th>
Texas
</th>
</tr>
<tr>
<th>
Lawson
</th>
<th>
21
</th>
<th>
Florida
</th>
</tr>
<tr>
<th>
Jose
</th>
<th>
25
</th>
<th>
London
</th>
</tr>
</table>