I have a simple script that works (or should) on page load and sorts a dynamically created list by the list items' Ids. It works fine in Firefox on both Windows and iPad Firefox but not on other browsers, including Chrome, Edge, my Android phone's browser or Amazon's Silk. I thought it might be something to do with my website so I put the code in Codepen and the issue is exactly the same there, too.
When I inspect the code in Chrome and Edge no errors are reported, so the code is just being ignored. Why?
Here is a slightly simplified version:
window.onload = function() {
let
list = document.querySelector('.list'),
results = document.querySelectorAll('.sort');
let sliced = Array.prototype.slice.call(results, 0);
sliced.sort(sortByElementId());
sliced.reduce(function(list, item) {
list.appendChild(item);
return list;
},
list);
function sortByElementId() {
return function(a, b) {
b.id;
a.id;
return a.id > b.id;
}
}
}
<div class="day-or-evening">
<h4>Meeting</h4>
<ul id="meetings" class="list">
<li id="id-22" class="sort li-22">Tuesday afternoon</li>
<li id="id-23" class="sort li-23">Tuesday evening</li>
<li id="id-25" class="sort li-25">Wednesday evening</li>
<li id="id-24" class="sort li-24">Wednesday morning</li>
<li id="id-27" class="sort li-27">Thursday evening</li>
<li id="id-17" class="sort li-17">Monday afternoon</li>
<li id="id-26" class="sort li-26">Thursday afternoon</li>
<li id="id-21" class="sort li-21">Monday evening</li>
</ul>
</div>
Your sort comparator function is invalid. A sort comparator must return (for arguments a and b) one of:
a should go before b in the result;b should go before a;a and b are already in order.If you don't do that, you can get inconsistent and incorrect sorting results. There is no guarantee that for any two elements in your array, for example, that they'll always be passed as a and b (instead of b and a).
For sorting arrays of numbers, subtracting one from the other results in a good return value. For strings, as in your case, you can use the .localeCompare() function of strings, though that has some possibly odd behavior in some special cases.