I’m receiving an array of objects in form of a json file, and using ajax to display certain key-value pairs in a table. My next step is to sort the rendered table, but I’m unsure of how to proceed.
<div id="data-table">
<table id="html-data-table">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</table>
</div>
Javascript code which creates the table:
newData.map(row => {
let newRow = document.createElement("tr"); // new row is created
Object.values(row).map((value) => {
//console.log(value);
let cell = document.createElement("td"); // new data for the row is added
cell.innerText = value;
newRow.appendChild(cell);
})
mytable.appendChild(newRow);
});
I want to sort this both columns individually. What method can I use?
2
Answers
You can use
Array.sort()
to sort your data, in this example I added two buttons to handle sorting byname
andage
:Here is a method of sorting the table in place, independent of any generating data structures. The only additionally required information is the
sortmode
array that specifies whether a text sort or a numeric sort is wanted for a particular column.