Introduction
I was browsing the web and came across a website talking about sorting in JavaScript and it got me thinking about creating a table with a data set where one property can be sorted and everything else in the data set complies with the change.
Background
The data set in question will be in JSON format. This can be generated from a PHP page, can be a file or even hard coded in your JavaScript. This data set forms the basis of the table. The attributes of the JSON object are subject to being sorted and the whole JSON data set changes when one attribute is sorted. In my case, I'll have a list of people with ages and marks resulting in a table that looks as follows:
The Code
var data = [
{ name: 'Kevin', age : 18, marks : 90 },
{ name: 'Murani', age : 19, marks : 87 },
{ name: 'Thathi', age : 17, marks : 67 },
{ name: 'Andrew', age : 18, marks : 94 },
{ name: 'John', age : 18, marks : 88 }
];
function populate(data, tbody, tfoot_total, tfoot_average) {
var i = 0;
var total = 0;
var average = 0;
var tr = '';
for(var obj in data) {
i++;
total += data[obj]['marks'];
tr += '<tr><td>' + i + '.</td><td>' +
data[obj]['name'] + '</td><td>' + data[obj]['age'] +
'</td><td>' + data[obj]['marks'] + '</td></tr>'
}
average = total/i;
tbody.innerHTML = tr;
tfoot_total.innerHTML = total;
tfoot_average.innerHTML = average;
}
This function deals with the population of the table with the data set. This function complements the sorting. The sorting should be done before calling this function. The sorting functions are in sets of two; one for ascending values and one for descending values. They look like so:
function sortnameasc(a, b) { return a.name > b.name; }
function sortnamedesc(a, b) { return a.name < b.name; }
function sortageasc(a, b) { return a.age - b.age; }
function sortagedesc(a, b) { return b.age - a.age; }
function sortmarksasc(a, b) { return a.marks - b.marks; }
function sortmarksdesc(a, b) { return b.marks - a.marks; }
We also need a way of determining which state the data is in, i.e., ascending, descending, or unsorted. For this, we'll use integer values of -1
for unsorted, 0
for ascending and 1
for descending.
With these values, we can then configure the sorting function. Each sort button will have its own event listener to determine the state of the data set, sort it accordingly and populate the table. An example for sorting the names looks as follows:
document.getElementsByTagName('span')[0].onclick = function() {
if(name_sort == -1 || name_sort == 1) {
data.sort(sortnameasc);
name_sort = 0;
} else {
data.sort(sortnamedesc);
name_sort = 1;
}
populate(data, tbody, tfoot_total, tfoot_average);
}
To understand the entire structure, browse the code.
Conclusion
This example uses pure JavaScript. No libraries or plugins required. I hope someone finds it useful and interesting enough to improve it. The ideal situation would be a one size fits all scenario instead of having to configure each attribute separately.