Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 871891
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T10:42:24+00:00 2026-05-15T10:42:24+00:00

I currently use the sort function to sort my div elements based on the

  • 0

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 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T10:42:25+00:00Added an answer on May 15, 2026 at 10:42 am

    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 sortDescending method gets two divs each time, and comparison must follow the criteria you’ve specified:

    1. First by count
    2. If count is equal, then by timestamp
    3. If timestamps are equal, then return 0

    Here’s the ugly straightforward non-optimized version:

    function sortDescending(a, b) {
        if(getCount(a) < getCount(b)) {
            return -1;
        }
        else if(getCount(a) > getCount(b)) {
            return 1;
        }
        else if(getTimestamp(a) < getTimestamp(b)) {
            return -1;
        }
        else if(getTimestamp(a) > getTimestamp(b) {
            return 1;
        }
        else {
            return 0;
        }
    }
    

    If you see the if-else structure, 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 a sortBy method that takes in a number callback functions, where each callback defines one sorting criteria.

    function sortBy() {
        var callbacks = arguments;
    
        return function(a, b) {
            for(var i = 0; i < callbacks; i++) {
                var value = callbacks[i](a, b);
                if(value != 0) {
                    return value;
                }
            }
            return 0;
        };
    }
    

    Then pass all criteria’s as callbacks to this sortBy function. Here’s a rough example for your code:

    function compareCount(a, b) {
        return getCount(a) - getCount(b);
    }
    
    function compareTimestamp(a, b) {
        return getTimestamp(a) - getTimestamp(b);
    }
    
    $("selector").sort(sortBy(compareCount, compareTimestamp));
    

    And while we are at it, let’s also make a jQuery plugin out of this. It will have a nice and easy interface:

    $("parent selector").sortBy("child selector 1", "child selector 2", ...);
    

    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.

    jQuery.fn.sortBy = function() {  
        var selectors = arguments;
    
        this.sort(function(a, b) {
            // run through each selector, and return first non-zero match
            for(var i = 0; i < selectors.length; i++) {
                var selector = selectors[i];
    
                var first = $(selector, a).text();
                var second = $(selector, b).text();
    
                var isNumeric = Number(first) && Number(second);
                if(isNumeric) {
                    var diff = first - second;
                    if(diff != 0) {
                        return diff;
                    }
                }
                else if(first != second) {
                    return first < second ? -1 : 1;
                }
            }
    
            return 0;
        });
    
        this.appendTo(this.parent());
    
        return this;
    };
    

    Use as

    $('#list .list_item').sortBy('.count', '.timestmap');
    

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am currently trying to make a special sort function for a Magento category
I currently use Zend_Db to manage my queries $stmt = $db->prepare(INSERT INTO test (ID_Test)
I currently use Devise 2.1 + Rails 3.2.x to authenticate users. I'm also going
I currently use the rectangle shape xml tag to specify borders for my views
I currently use a combination of LVL and Proguard as a first line of
I currently use mysql_real_escape_string to escape a variable when querying the database to prevent
I currently use Berkeley DBs fronted by a Java server for a high-performance disk-backed
I currently use: BufferedReader input = new BufferedReader(new FileReader(filename)); Is there a faster way?
I currently use the free obfuscation tool that ships with VS and it does
I currently use a System.IO.FileSystemWatcher as part of a roll your own message queue

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.