Skip to content

Instantly share code, notes, and snippets.

@m3g4p0p
Last active September 20, 2016 20:24
Show Gist options
  • Save m3g4p0p/b39aff841be6e3770ad504e72eabe26f to your computer and use it in GitHub Desktop.
Save m3g4p0p/b39aff841be6e3770ad504e72eabe26f to your computer and use it in GitHub Desktop.
Generate a sortable table from a data array
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;
};
@m3g4p0p
Copy link
Author

m3g4p0p commented Sep 20, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment