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
+4.8k Fix yum-complete-transaction error
+4.3k Golang : Calculate half life decay example
+12.5k Golang : Activate web camera and broadcast out base64 encoded images
+4.5k Golang : Reclaim memory occupied by make() example
+12.1k Golang : How to get a user home directory path?
+5.6k Golang : Embedded or data bundling example
+9.7k Golang : Get UDP client IP address and differentiate clients by port number
+10.9k Golang : Pagination with go-paginator configuration example
+15.7k Golang : Get own process identifier
+4.6k How to check with curl if my website or the asset is gzipped ?
+24.7k Golang : Get executable name behind process ID example
+5.2k Golang : Convert Chinese UTF8 characters to Pin Yin