Javascript : Shuffle or randomize array example
Problem :
You have an array and you want to shuffle the items in the array. How to do that in Javascript?
Solution :
Use Math.random()
function to randomize the swapping process and the end result will be a shuffled/randomized array.
function shuffle(input){
for(
var j, x, i = input.length; i;
j = Math.floor(Math.random() * i),
x = input[--i],
input[i] = input[j],
input[j] = x
);
return input;
};
var intArray = ['0','1','2','3','4','5','6','7','8','9'];
shuffle(intArray);
console.log(intArray);
var strArray = ['abc','def','ghi','jkl','mno'];
shuffle(strArray);
console.log(strArray);
To see the output, use the browser's console viewer.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.9k Golang : Convert octal value to string to deal with leading zero problem
+37.8k Golang : Remove dashes(or any character) from string
+7.5k Golang : How to capture return values from goroutines?
+16.1k Golang : Multi threading or run two processes or more example
+4.6k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+7.3k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+6k Golang : Fibonacci number generator examples
+5.7k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+4.5k Clean up Visual Studio For Mac installation failed disk full problem
+16.1k Golang : Find smallest number in array
+32.3k Golang : All update packages with go get command
+4.9k Get website traffic ranking with Similar Web or Alexa