Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active September 18, 2023 11:04
Show Gist options
  • Save code-boxx/45ebe489b99583dc170564113b1ad24e to your computer and use it in GitHub Desktop.
Save code-boxx/45ebe489b99583dc170564113b1ad24e to your computer and use it in GitHub Desktop.
Javascript Sortable Table

JAVASCRIPT SORTABLE TABLE

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<!DOCTYPE html>
<html>
<head>
<title>JS Sortable Table</title>
<!-- (A) JS + CSS -->
<link rel="stylesheet" href="sortable.css">
<script src="sortable.js"></script>
</head>
<body>
<!-- (B) TABLE : NEEDS PROPER THEAD TBODY -->
<table id="demoA">
<thead>
<tr>
<td>Fruit</td>
<td>Color</td>
</tr>
</thead>
<tbody>
<tr>
<td>Durian</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
<tr>
<td>Apple</td>
<td>Red</td>
</tr>
<tr>
<td>Grape</td>
<td>Red</td>
</tr>
<tr>
<td>Blueberry</td>
<td>Blue</td>
</tr>
<tr>
<td>Pear</td>
<td>Green</td>
</tr>
</tbody>
</table>
<!-- (C) INITIALIZE -->
<script>
sortable(document.getElementById("demoA"));
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JS Sortable Table</title>
<!-- (A) JS + CSS -->
<link rel="stylesheet" href="sortable.css">
<script src="sortable.js"></script>
</head>
<body>
<!-- (B) EMPTY TABLE -->
<table id="demoB"></table>
<!-- (C) INITIALIZE -->
<script>
sortable(document.getElementById("demoB"), {
ID : [44, 11, 7, 5, 2],
Name : ["John Doe", "Jane Doe", "Aaron Doe", "Zoe Doe", "Derrick Doe"],
Color : ["Red", "Green", "Blue", "White", "Red"]
});
</script>
</body>
</html>
/* CSS IS OPTIONAL - FOR COSMETICS ONLY */
/* FEEL FREE TO CREATE YOUR OWN STYLES & DISCARD THIS */
/* (A) SORTABLE TABLE */
.sorta { border-collapse: collapse; }
/* (B) CELLS */
.sorta td, .sorta th {
padding: 10px;
text-align: left;
}
/* (C) HEADER */
.sorta thead {
font-weight: 700;
color: #fff;
background: #000;
}
.sorta thead *::selection { background: none; }
/* (D) BODY */
.sorta tbody tr:nth-child(even) { background: #f2f2f2; }
/* (E) UP/DOWN COLORS */
.sortup { background: #a11010; }
.sortdown { background: #2c2cf9; }
.sortup::before, .sortdown::before { padding-right: 5px; }
.sortup::before { content: "\21E7"; }
.sortdown::before { content: "\21E9"; }
/* (X) DOES NOT MATTER */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
// instance : target html table
// data : optional, generate table with this data
function sortable (instance, data) {
// (A) FLAGS
instance.sBy = null; // sort by this column
instance.sDirection = true; // ascending/descending order
instance.sOrder = []; // calculated sort order
// (B) SORT FUNCTION
instance.sort = selected => {
// (B1) UPDATE SORT FLAGS
if (instance.sBy == selected.innerHTML) {
instance.sDirection = !instance.sDirection;
} else {
instance.sBy = selected.innerHTML;
instance.sDirection = true;
}
// (B2) UPDATE CSS OF HEADER CELLS
for (let c of instance.head.rows[0].cells) {
c.classList.remove("sortup");
c.classList.remove("sortdown");
if (c == selected) {
c.classList.add((instance.sDirection ? "sortup" : "sortdown"));
}
}
// (B3) MAP OUT DATA OF THE SELECTED COLUMN
// I.E. WE NEED TO RETAIN THE INDEX POSITIONS WHILE SORTING
let map = data[selected.innerHTML].map((v, i) => { return { i: i, v: v }; });
// (B4) SORT ARRAY
if (instance.sDirection) {
map.sort((a, b) => {
if (a.v > b.v) { return 1; }
if (a.v < b.v) { return -1; }
return 0;
});
} else {
map.sort((a, b) => {
if (a.v < b.v) { return 1; }
if (a.v > b.v) { return -1; }
return 0;
});
}
// (B5) REDRAW TABLE WITH NEW SORT ORDER
instance.sOrder = [];
for (let idx in map) { instance.sOrder.push(map[idx].i); }
instance.draw();
};
// (C) DRAW HTML TABLE
instance.draw = () => {
// (C1) REMOVE OLD SORT ORDER
instance.body.innerHTML = "";
// (C2) DRAW NEW SORT ORDER
let r, c;
for (let i of instance.sOrder) {
r = instance.body.insertRow();
for (let key in data) {
c = r.insertCell();
c.innerHTML = data[key][i];
}
}
};
// (D) ADAPT DATA FROM EXISTING TABLE
if (data==undefined) {
// (D1) GET TABLE SECTIONS
instance.head = instance.querySelector("thead");
instance.body = instance.querySelector("tbody");
// (D2) GET DATA FROM HEADER
data = {}; keys = [];
for (let c of instance.head.rows[0].cells) {
data[c.innerHTML] = [];
keys.push(c.innerHTML);
}
// (D3) GET DATA FROM BODY
for (let r of instance.body.rows) { for (let i=0; i<r.cells.length; i++) {
data[keys[i]].push(r.cells[i].innerHTML);
}}
delete(keys);
}
// (E) DRAW SORTABLE TABLE FROM OBJECT
else {
// (E1) CREATE TABLE SECTIONS
instance.head = instance.createTHead();
instance.body = instance.createTBody();
// (E2) HEADER CELLS
let r = instance.head.insertRow();
r = instance.head.rows[0];
for (let key in data) {
let c = r.insertCell();
c.innerHTML = key;
}
// (E3) DEFAULT SORT ORDER & DRAW BODY
for (let i=0; i<data[Object.keys(data)[0]].length; i++) { instance.sOrder.push(i); }
instance.draw();
}
// (F) CLICK ON HEADER CELL TO SORT
instance.classList.add("sorta");
for (let r of instance.head.rows) {
for (let c of r.cells) {
c.onclick = () => instance.sort(c);
}}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment