YogeshChauhan.com
How to Sort (Shuffle) an Array in Random Order in JavaScript?
August 12, 2020

Solution 1


var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 - Math.random()});
// [ 1, 100, 40, 10, 25, 5 ]

points.sort(function(a, b){return 0.5 - Math.random()});
// [ 5, 1, 25, 100, 10, 40 ]

...
...

Solution 2


var points = [40, 100, 1, 5, 25, 10];
var i, j, k;
for (i = points.length - 1; i > 0; i--) {
  j = Math.floor(Math.random() * i);
  k = points[i];
  points[i] = points[j];
  points[j] = k;
}
console.log(points);
// [ 10, 40, 100, 1, 5, 25 ]

console.log(points);
// [ 10, 40, 25, 100, 5, 1 ]

...
...

Make a function..


var points = [40, 100, 1, 5, 25, 10];
function myFunction() {
var i, j, k;
  for (i = points.length -1; i > 0; i--) {
    j = Math.floor(Math.random() * i)
    k = points[i]
    points[i] = points[j]
    points[j] = k
  }
  console.log(points) ;
}
myFunction();
// [ 10, 5, 25, 1, 40, 100 ]

myFunction();
// [ 1, 25, 100, 10, 5, 40 ]

Solution 3


function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex
  // While there remain elements to shuffle...
  while (0 !== currentIndex) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  return array;
}

var points = [40, 100, 1, 5, 25, 10];
shuffle(points);

console.log(points);
// [ 40, 100, 5, 10, 1, 25 ]

console.log(points);
[ 40, 1, 5, 10, 100, 25 ]

Sources

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 5 How to create flickering text using CSS? Mar 4 How to use data-* Attributes in HTML? Mar 4 The substr() method in JavaScript and how it’s different from substring() Mar 4 A complete guide to add responsive YouTube videos using HTML and CSS Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress?

You might also like these

Killing A Project Part 1: What criteria should be used to cancel/kill a project?MiscHow to import MySQL small sample database into phpMySQL?SQL/MySQL2 Ways we can create an Array in JavaScriptJavaScriptHow to create Glowing Text using CSS?CSSHow to Create a Backup From Any Database in SQL?SQL/MySQLHow to obfuscate JavaScript code to hide it from View Source?JavaScript