I currently use the sort function to sort my div elements based on the count value. Here’s how it’s being done now: (I’m not sure if it’s an efficient method or not..)
$('#list .list_item').sort(sortDescending).appendTo('#list');
function sortDescending(a, b) {
return $(a).find(".count").text() < $(b).find(".count").text() ? 1 : -1;
};
I’m thinking of adding a timestamp field and am unsure how I can extend it to support this.
I have a list of div elements with its own count and date/time/timestamp. Here’s how the html code would look like:
<div id="list">
<div id="list_item_1" class="list_item">
<div class="count">5</div>
<div class="timestamp">1272217086</div>
<div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis quis ipsum rutrum metus rhoncus feugiat non vel orci. Etiam sit amet nisi sit amet est convallis viverra</div>
</div>
<div id="list_item_2" class="list_item">
<div class="count">5</div>
<div class="timestamp">1272216786</div>
<div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis quis ipsum rutrum metus rhoncus feugiat non vel orci. Etiam sit amet nisi sit amet est convallis viverra</div>
</div>
<div id="list_item_3" class="list_item">
<div class="count">10</div>
<div class="timestamp">1272299966</div>
<div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis quis ipsum rutrum metus rhoncus feugiat non vel orci. Etiam sit amet nisi sit amet est convallis viverra</div>
</div>
</div>
I would like to sort by count (decreasing), followed by timestamp (decreasing – newest at the top).
Any help is greatly appreciated! Thanks 🙂
Only the sort comparator function needs to change. I’m sure there are plugins available to do this, and you might want to take a look at them, but implementing what you want is fairly trivial. The
sortDescendingmethod gets two divs each time, and comparison must follow the criteria you’ve specified:Here’s the ugly straightforward non-optimized version:
If you see the
if-elsestructure, it may seem obvious that you can genericize this approach to be able to handle any type of custom ordering. So here’s a jab at asortBymethod that takes in a number callback functions, where each callback defines one sorting criteria.Then pass all criteria’s as callbacks to this
sortByfunction. Here’s a rough example for your code:And while we are at it, let’s also make a jQuery plugin out of this. It will have a nice and easy interface:
The idea is to pass a jQuery selector that will select a node whose text will determine the value to sort by. We will give integers a higher priority and first try to sort numerically if both values are so, otherwise do a regular comparison.
Use as
See an example of the plugin here.
Btw, none of this will actually sort the elements in the document itself. See this question for how to do that.