Created
September 22, 2023 23:51
-
-
Save Shimilbi/a7f4d65ed333e7df0edb806c7e858ec4 to your computer and use it in GitHub Desktop.
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
var ascending = true | |
var lastFieldName = '' | |
function SortBy(arr, fieldName) { | |
if (ascending) { | |
arr.sort((p1, p2) => { | |
if (p1[fieldName] < p2[fieldName]) return -1 | |
if (p1[fieldName] > p2[fieldName]) return 1 | |
return 0 | |
}) | |
} | |
else if (!ascending) { | |
arr.sort((p1, p2) => { | |
if (p1[fieldName] > p2[fieldName]) return -1 | |
if (p1[fieldName] < p2[fieldName]) return 1 | |
return 0 | |
}) | |
} | |
if (fieldName==lastFieldName) | |
if (ascending===true) ascending = false | |
else ascending =true | |
else | |
lastFieldName = fieldName | |
return arr | |
} | |
function DisplayTable(arr, fieldName) { | |
let sortedArray = SortBy(arr, fieldName) | |
let line = '<tr><th>Name</th><th>Money</th></tr>' | |
sortedArray.forEach(p => { | |
line += '<tr><td>' + p.name + '</td><td>' + p.money + '</td></tr>' | |
}) | |
document.querySelector('table').innerHTML = line | |
document.querySelector('th').addEventListener('click', e => { | |
DisplayTable(arr, e.target.textContent.toLowerCase()) | |
e.target.innerHTML += ascending ? ' 🠹' : ' 🠻' // bug: this is skipped | |
}) | |
document.querySelector('th + th').addEventListener('click', e => { | |
DisplayTable(arr, e.target.textContent.toLowerCase()) | |
e.target.innerHTML += ascending ? ' 🠹' : ' 🠻' // bug: this is skipped | |
}) | |
} | |
/** | |
For use like this: | |
<!DOCTYPE html> | |
<html> | |
<body> | |
<h1>Persons</h1> | |
<h2>(Stable Sort)</h2> | |
<table></table> | |
</body> | |
<script> | |
document.addEventListener('DOMContentLoaded', () => { | |
DisplayTable(<myArray>, '<myFirstFieldName>') | |
document.querySelector('th').innerHTML += ' 🠻' | |
document.querySelector('th + th').innerHTML += '' | |
}) | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Harmless bug: need to click twice on each new column to sort by (then only once)
Can be improved: Doesn't display a cue of the current sorting order in the table header)