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);
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);
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]];
}
}
How to achieve a sorted but random list with javascript/jquery - Stack Overflow
javascript Sort list randomly - Stack Overflow
How does Math.random work to sort an array?
javascript - Sorting an Array in Random Order - Stack Overflow
Videos
You'll need to implement a shuffle algorithm, for example
var arr = [20, 22, 24];
function shuffleArray(a) { // Fisher-Yates shuffle, no side effects
if(a.length === 0) return a;
var i = a.length, t, j;
a = a.slice();
while (--i) t = a[i], a[i] = a[j = ~~(Math.random() * (i+1))], a[j] = t;
return a;
}
shuffleArray(arr); // [22, 24, 20]
shuffleArray(arr); // [22, 20, 24]
shuffleArray(arr); // [24, 22, 20]
Somewhat simpler than the other options if you don't mind the original array being modified:
function randomizeArray(arr) {
var output = [];
while (arr.length) {
output.push(arr.splice(Math.floor(Math.random() * arr.length), 1)[0]);
}
return output;
}
This cycles through the original array and selects a random index each time, then adds the element at that index to the destination array and removes it from the original array. Then, repeat process until original array is empty.
Working demo here: http://jsfiddle.net/jfriend00/7jhs7/
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);
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.
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.
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 ..