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 9030919
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T07:36:29+00:00 2026-06-16T07:36:29+00:00

I got this piece of code from a website for randomizing a list of

  • 0

I got this piece of code from a website for randomizing a list of items. [This is for a music player that randomizes the songs (list) in every new visit by the user, thus not boring them by starting with the same song that they heard in the past visit]

    $(document).ready(function(){
      $('ul').each(function(){
            // get current ul
            var $ul = $(this);
            // get array of list items in current ul
            var $liArr = $ul.children('li');
            // sort array of list items in current ul randomly
            $liArr.sort(function(a,b){
                  // Get a random number between 0 and 10
                  var temp = parseInt( Math.random()*10 );
                  // Get 1 or 0, whether temp is odd or even
                  var isOddOrEven = temp%2;
                  // Get +1 or -1, whether temp greater or smaller than 5
                  var isPosOrNeg = temp>5 ? 1 : -1;
                  // Return -1, 0, or +1
                  return( isOddOrEven*isPosOrNeg );
            })
            // append list items to ul
            .appendTo($ul);            
      });
});

This works perfectly fine when I open my site in Chrome browser. The sorting is done pretty heavily and hence I could see that the list is randomized to a great extent.

But in Firefox and IE, the sorting is not happening to a good extent. I see that the first list item remains first in 7 out of 10 tries. And I could see the same for many other items. Ex: Item #5 occur in 3rd position in 5 out of 10 tries. With these observations, I could tell that the JS code is not working properly in IE and Firefox. (may be due to the way different browsers treat JS code because of the differences in the engine)

Now, Is there anything I can change in the JS code to make it work in all browsers?

Or Is there any other better sorting algorithm that would do a decent sorting in all browsers when implemented using JS?

I understand that a part of my 2nd question has been answered in other questions within SE but I couldn’t find about the ‘browser compatibility’ part in those questions.

Thanks for helping.

  • 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-06-16T07:36:30+00:00Added an answer on June 16, 2026 at 7:36 am

    Your randomisation is not very good:

    // Get a random number between 0 and 10
    var temp = parseInt( Math.random()*10 );
    // Get 1 or 0, whether temp is odd or even
    var isOddOrEven = temp%2;
    // Get +1 or -1, whether temp greater or smaller than 5
    var isPosOrNeg = temp>5 ? 1 : -1;
    // Return -1, 0, or +1
    return( isOddOrEven*isPosOrNeg );
    

    That means in a half of the cases you return 0, which tells the sort function that the two items are equal. A good sort function will notice that and not ask again. With only a few items, you have a very high chance of the items not getting sorted well. You can proof this by counting (logging) how often your compare-function is called.

    Also you don’t need to return only +1, 0 or -1, you can just return any positive or negative number (see also below). For randomizing, you never really need to return equality. So, use this instead:

    ….sort( function() {
         return 0.5 - Math.random(); // that would be enough!
    } );
    

    However, one should not use sort for randomisation at all. Math.random does not lead to a total ordering, and sort is not made for that: (from the EcmaScript specification)

    If comparefn is […] not a consistent comparison function for the elements of this array, the behaviour of sort is implementation-defined.

    A function comparefn is a consistent comparison function for a set of values S if all of the requirements below are met for all values a, b, and c (possibly the same value) in the set S: The notation a <CF b means comparefn(a,b) < 0; a =CF b means comparefn(a,b) = 0 (of either sign); and a >CF b means comparefn(a,b) > 0.

    Calling comparefn(a,b) always returns the same value v when given a specific pair of values a and b as its two arguments. Furthermore, Type(v) is Number, and v is not NaN. Note that this implies that exactly one of a <CF b, a =CF b, and a >CF b will be true for a given pair of a and b.

    • Calling comparefn(a,b) does not modify the this object.
    • a =CF a (reflexivity)
    • If a =CF b, then b =CF a (symmetry)
    • If a =CF b and b =CF c, then a =CF c (transitivity of =CF)
    • If a <CF b and b <CF c, then a <CF c (transitivity of <CF)
    • If a >CF b and b >CF c, then a >CF c (transitivity of >CF)

    NOTE: The above conditions are necessary and sufficient to ensure that comparefn divides the set S into equivalence classes and that these equivalence classes are totally ordered.

    An optimised sort function can easily screw up if these properties are not fulfilled. That can mean no sorting at all as well as never terminating sorting. See Is it correct to use JavaScript Array.sort() method for shuffling?

    Instead, use a standard shuffle algorithm, there are many good ones. The Fisher-Yates-Shuffle is really simple to implement for example, see the question How to randomize (shuffle) a JavaScript array?.

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

Sidebar

Related Questions

I got this piece of Assembly code extracted from some piece of software, but
I've got this really simple piece of code that I thought was the correct
I have got a piece of code, that should countdown some number (in this
I've got this piece of code from a Backbone.js tutorial from here . The
I've got this piece of code, where I gather device id from different types
I have this small piece of code I got from a friend, but i
I got this piece of code from a book viz. sams teach yourself android
I got this piece of code from Mysql 4th edition to check table existence
I got this piece of code from somewhere in stackoverflow. I am unable to
I've got this piece of code to toggle a side panel: $(.example_wrapper_panel_link).click(function() { $(.example_wrapper).addClass('example_wrapper_active');

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.