Last active
September 20, 2016 20:24
-
-
Save m3g4p0p/b39aff841be6e3770ad504e72eabe26f to your computer and use it in GitHub Desktop.
Generate a sortable table from a data array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const sortable = function(data) { | |
const table = document.createElement('table'); | |
const thead = document.createElement('thead'); | |
const tbody = document.createElement('tbody'); | |
const currentOrder = {}; | |
// Function to populate the tbody with the data | |
const _populate = current => { | |
const row = tbody.insertRow(); | |
row.innerHTML = Object | |
.keys(current) | |
.reduce((carry, key) => | |
carry + `<td>${current[key]}</td>`, | |
'' | |
); | |
}; | |
// Create the thead from the object keys | |
thead.innerHTML = '<tr>'+ | |
Object | |
.keys(data[0]) | |
.reduce((carry, current) => | |
carry + `<th data-key="${current}">${current}</th>`, | |
`` | |
) + | |
'</tr>'; | |
// Add an event listener to sort the data according | |
// to the clicked th | |
thead.addEventListener('click', function(event) { | |
const key = event.target.dataset.key; | |
const sorted = currentOrder[key] | |
? data = data.sort((a, b) => a[key] < b[key] ? 1 : -1) | |
: data = data.sort((a, b) => a[key] > b[key] ? 1 : -1); | |
currentOrder[key] = !currentOrder[key]; | |
tbody.innerHTML = ''; | |
sorted.forEach(_populate); | |
}); | |
// Initialise and return the table | |
data.forEach(_populate); | |
table.appendChild(thead); | |
table.appendChild(tbody); | |
return table; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo: http://m3g4p0p.bplaced.net/sortable/