The de-facto unbiased shuffle algorithm is the Fisher–Yates (aka Knuth) Shuffle.

You can see a great visualization here.

function shuffle(array) {
  let currentIndex = array.length;

  // While there remain elements to shuffle...
  while (currentIndex != 0) {

    // Pick a remaining element...
    let randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }
}

// Used like so
let arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);

Top answer
1 of 16
2621

The de-facto unbiased shuffle algorithm is the Fisher–Yates (aka Knuth) Shuffle.

You can see a great visualization here.

function shuffle(array) {
  let currentIndex = array.length;

  // While there remain elements to shuffle...
  while (currentIndex != 0) {

    // Pick a remaining element...
    let randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }
}

// Used like so
let arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);

2 of 16
1276

Here's a JavaScript implementation of the Durstenfeld shuffle, an optimized version of Fisher-Yates:

/* Randomize array in-place using Durstenfeld shuffle algorithm */
function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

It picks a random element for each original array element, and excludes it from the next draw, like picking randomly from a deck of cards.

This clever exclusion swaps the picked element with the current one, then picks the next random element from the remainder, looping backwards for optimal efficiency, ensuring the random pick is simplified (it can always start at 0).

Note the loop condition skips i==0, since j can only ever be 0 then, leading to no swap.

Algorithm runtime is O(n). Note that the shuffle is done in-place so if you don't want to modify the original array, first make a copy of it with .slice(0).


EDIT: Updating to ES6 / ECMAScript 2015

The new ES6 allows us to assign two variables at once. This is especially handy when we want to swap the values of two variables, as we can do it in one line of code. Here is a shorter form of the same function, using this feature.

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › data types › array methods
Shuffle an array
Write the function shuffle(array) that shuffles (randomly reorders) elements of the array.
Discussions

How to achieve a sorted but random list with javascript/jquery - Stack Overflow
Or would pure javascript handle this more efficiently? ... OPTIONAL - if you want the stores in order, pad the number with zeros and append an identifier for the store ([padded item number]|[store identifier] eg 00001|A) ... Thanks for the quick answer! I've been working on it for awhile without much headway--I think I understand though. I randomly sort the individual lists... More on stackoverflow.com
🌐 stackoverflow.com
javascript Sort list randomly - Stack Overflow
guess I have a list with the next: 20 22 24 how can I sort the three elements randomly so I get stuff like 22, 20, 24 or 24,20,22? I know you can generate random numbers but I think I'm not look... More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
How does Math.random work to sort an array?
I had learned about the sort method, but got stuck at the random sorting part. I know we can use this: array.sort (function(a, b) { return 0.5 - Math.random()}); to create a random sorted array, but how does it work? This is what I know so far: array.sort(function(a, b){return a - b}); it will ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
2
October 5, 2017
javascript - Sorting an Array in Random Order - Stack Overflow
And for that random in the built-in sort function is a terrible practice, because it is biased towards the initial state, meaning that the elements in the "shuffled" array will tend to stay near their positions (those that were near the beginning have the high probability of staying near the beginning, etc...). The bigger the size the array grows, the less it gets shuffled. Here is the proof: Is it correct to use JavaScript ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
DEV Community
dev.to › codebubb › how-to-shuffle-an-array-in-javascript-2ikj
How to shuffle an array in JavaScript - DEV Community
October 16, 2020 - As the function we pass to .sort() is looking for either a positive or negative number to either move the item ‘up’ or ‘down’ in the array, each item has a chance of being moved in either direction giving us a shuffled array of items. This works for a rough-and-ready approach but might not give you a truly random shuffle.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-shuffle-an-array-using-javascript
How to Shuffle an Array using JavaScript ? - GeeksforGeeks
November 11, 2024 - To shuffle a JavaScript array we can use the Fisher-Yates shuffle also known as knuth shuffle. It will sort the given array in a random order with the help of the math.random() function.
🌐
W3docs
w3docs.com › javascript
How to Randomize (shuffle) a JavaScript Array
function shuffleArray(array) { let curId = array.length; // There remain elements to shuffle while (0 !== curId) { // Pick a remaining element let randId = Math.floor(Math.random() * curId); curId -= 1; // Swap it with the current element. let ...
🌐
Kodyaz
kodyaz.com › articles › sort-array-in-random-order-using-javascript-shuffle-function.aspx
Sort Array in Random Order using Javascript Shuffle Function
You can see the javascript sort ... check the codes of sort function random_sort() they will see it consists of a single line of code calling Math.random() method....
🌐
DEV Community
dev.to › areeburrub › randomly-sort-array-in-one-just-line-2oab
Randomly Sort Array in just one line; - DEV Community
May 17, 2021 - so here Math.random(); give between 0 to 1 and its subtracted from 0.5 . We use sort() function, Inside sort we put a compare function which is have chances to return postive or negetive number 50/50 and thats how we are getting random sorted Array
Find elsewhere
🌐
Codemzy
codemzy.com › blog › shuffle-array-javascript
How to shuffle an array into a random order with JavaScript - Codemzy's Blog
July 20, 2023 - let shuffled = deckOfCards.sort(() => Math.random() - 0.5); ... We can use Array.sort() to sort an array in JavaScript, but instead of sorting by string, object property, or number, we just want to sort randomly.
🌐
TutorialsPoint
tutorialspoint.com › How-to-randomize-shuffle-a-JavaScript-array
How to randomize (shuffle) a JavaScript array?
September 6, 2022 - If you need a copy of the original array, you can use the spread operator syntax given below. arr.sort(function(a, b) { return Math.random() - 0.5; }); //Arrow function syntax arr.sort(() => Math.random() - 0.5); //The spread operator syntax [...arr].sort(() => Math.random() - 0.5);
🌐
Stack Overflow
stackoverflow.com › questions › 24657743 › how-to-achieve-a-sorted-but-random-list-with-javascript-jquery
How to achieve a sorted but random list with javascript/jquery - Stack Overflow
$(document).ready(function () { (function ($) { $.fn.randomize = function (childElem) { return this.each(function () { var $this = $(this); var elems = $this.children(childElem); elems.sort(function () { return (Math.round(Math.random()) - 0.5); }); $this.remove(childElem); for (var i = 0; i < elems.length; i++) $this.append(elems[i]); }); }; })(jQuery); (function ($) { if (window.location.href.indexOf("st=") > -1) { } else { $('#itemBlock').randomize('.list_1'); } })(jQuery); });
🌐
freeCodeCamp
freecodecamp.org › news › how-to-shuffle-an-array-of-items-using-javascript-or-typescript
How to Shuffle an Array of Items Using JavaScript or TypeScript
June 5, 2023 - This random value will cause the comparison function to return negative, positive, or zero values in a random manner for different pairs of elements. Consequently, the sort() method shuffles the array randomly.
🌐
Medium
medium.com › @nitinpatel_20236 › how-to-shuffle-correctly-shuffle-an-array-in-javascript-15ea3f84bfb
How To Correctly Shuffle An Array in JavaScript | by Nitin Patel | Medium
September 6, 2019 - 1. Write down the numbers from 1 through N. 2. Pick a random number k between one and the number of unstruck numbers remaining (inclusive). 3. Counting from the low end, strike out the kth number not yet struck out, and write it down at the ...
🌐
freeCodeCamp
forum.freecodecamp.org › t › how-does-math-random-work-to-sort-an-array › 151540
How does Math.random work to sort an array? - The freeCodeCamp Forum
October 5, 2017 - This is what I know so far: array.sort(function(a, b){return a - b}); it will sort the array from small number to bigger number, it’s because the value which a - b returns is negative, so the smaller number will be in the front. vice versa, ...
🌐
W3Schools
w3schools.com › js › js_array_sort.asp
JavaScript Array Sort
Using a sort function, like explained above, you can sort an numeric array in random order
🌐
Educative
educative.io › answers › how-to-shuffle-an-array-in-javascript
How to shuffle an array in JavaScript
Let’s write a shuffle function to randomly reorder elements of the array.
Top answer
1 of 7
19

You used

var as = ["max","jack","sam"];  
var s = as.sort(func);  

function func(a, b) {  
  return 0.5 - Math.random();
}  

console.log(s);

And here the most important thing is as.sort(func).
func(a,b) will return value in range of [-0.5,0.5].

Because this function return 0.5 - Math.random() and Math.random() will return the float value which is in range of [0,1].
So that your func will return value in range of [-0.5,0.5].

And this mean that sort order will be set increase or decrease. this is random. So your result will be random

var as = ["max","jack","sam"];  
var s = as.sort(func);  

function func(a, b) {  
  return Math.random();
}  

console.log(s);

var as = ["max","jack","sam"];  
var s = as.sort(func);  

function func(a, b) {  
  return 0 - Math.random();
}  

console.log(s);

var as = ["max","jack","sam"];  
var s = as.sort(func);  

function func(a, b) {  
  return 0.5 - Math.random();
}  

console.log(s);

2 of 7
14

Math.random() returns a number between 0 and 1 (exclusive). We're using 0.5 because it is the mean value.

Array.sort() sorts the parameters based on the return value. So, 0.5 - Math.random() will yield either positive or negative value with equal probability. Hence, it will sort the parameters randomly.

How it really works

  • If the return value of Array.sort() is positive, then the index of the first parameter will be higher than that of the second.
  • If it is negative, then the index of the second parameter will be higher than that of the first.
  • And, if it is 0, then do nothing.
Top answer
1 of 2
39

Look at this question and answer thread. I like this solution via the user gruppler:

$.fn.randomize = function(selector){
    var $elems = selector ? $(this).find(selector) : $(this).children(),
        $parents = $elems.parent();

    $parents.each(function(){
        $(this).children(selector).sort(function(){
            return Math.round(Math.random()) - 0.5;
        // }). remove().appendTo(this); // 2014-05-24: Removed `random` but leaving for reference. See notes under 'ANOTHER EDIT'
        }).detach().appendTo(this);
    });

    return this;
};

EDIT: Usage instructions below.

To randomize all <li> elements within each '.member' <div>:

$('.member').randomize('li');

To randomize all children of each <ul>:

$('ul').randomize();

ANOTHER EDIT: akalata has let me know in the comments that detach() can be used instead of remove() with the main benefit being if any data or attached listeners are connected to an element and they are randomized, detach() will keep them in place. remove() would just toss the listeners out.

2 of 2
0

I also stuck to such questions I search on google and come across one code. I modify this code for my uses. I also include the shuffle the list after 15 seconds.

<script>
 // This code helps to shuffle the li ...
(function($){
       $.fn.shuffle = function() {
         var elements = this.get()
         var copy = [].concat(elements)
         var shuffled = []
         var placeholders = []
         // Shuffle the element array
         while (copy.length) {
           var rand = Math.floor(Math.random() * copy.length)
           var element = copy.splice(rand,1)[0]
           shuffled.push(element)
         }

         // replace all elements with a plcaceholder
         for (var i = 0; i < elements.length; i++) {
           var placeholder = document.createTextNode('')
           findAndReplace(elements[i], placeholder)
           placeholders.push(placeholder)
         }

         // replace the placeholders with the shuffled elements
         for (var i = 0; i < elements.length; i++) {
           findAndReplace(placeholders[i], shuffled[i])
         }

         return $(shuffled)
       }

       function findAndReplace(find, replace) {
         find.parentNode.replaceChild(replace, find)
       }

       })(jQuery);

       // I am displying the 6 elements currently rest elements are hide.

       function listsort(){
       jQuery('.listify_widget_recent_listings ul.job_listings').each(function(index){
         jQuery(this).find('li').shuffle();
         jQuery(this).find('li').each(function(index){
           jQuery(this).show();
           if(index>=6){
             jQuery(this).hide();
           }
         });
       });
       }
       // first time call to function ...
       listsort();
       // calling the function after the 15seconds.. 
       window.setInterval(function(){
         listsort();
         /// call your function here 5 seconds.
       }, 15000);                 
</script>

Hope this solution helps....Have a great working time ..

🌐
Reddit
reddit.com › r/programming › array.sort() should not be used to shuffle an array -- you do not get a random distribution. (just a gentle reminder, since i've seen some people trying to use this recently.)
r/programming on Reddit: Array.sort() should not be used to shuffle an array -- you do not get a random distribution. (Just a gentle reminder, since I've seen some people trying to use this recently.)
March 25, 2011 - Deterministic shuffling, like a hash with no salt, can work if you only want to shuffle a list once, and if you don't care if someone figures out and exploits your shuffling algorithm. ... The code in the article isn't using sort properly. For sort() to work, we need to provide a comparator that implements a total ordering function (in the mathematical sense of the word). The key mistake is that the author gives a comparator, the one that generates random numbers at comparison time, that violates that expectation.
🌐
Saturn Cloud
saturncloud.io › blog › how-to-randomize-shuffle-a-javascript-array
How to Randomize Shuffle a JavaScript Array | Saturn Cloud Blog
October 4, 2023 - The comparison function returns a random number between -0.5 and 0.5, which ensures that the elements are sorted randomly. One disadvantage of using the sort method to shuffle an array is that it is not as efficient as the Fisher-Yates shuffle algorithm. The sort method has an average time complexity of O(n log n), which is slower than the O(n) time complexity of the Fisher-Yates shuffle algorithm. Underscore.js is a popular JavaScript library that provides a variety of utility functions, including a shuffle method for arrays.