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
+25.4k Golang : How to write CSV data to file
+5.4k Unix/Linux/MacOSx : Get local IP address
+9.1k Mac OSX : Get a process/daemon status information
+7.9k Golang : Auto-generate reply email with text/template package
+7.3k Golang : Detect sample rate, channels or latency with PortAudio
+6.9k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+26.4k Golang : How to check if a connection to database is still alive ?
+6.9k Golang : Array mapping with Interface
+10.7k Golang : Create Temporary File
+4.6k Fix Google Analytics Redundant Hostnames problem
+6.6k Golang : How to solve "too many .rsrc sections" error?
+15.1k Golang : invalid character ',' looking for beginning of value