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.2k Golang *File points to a file or directory ?
+4.5k Swift : Convert string array to array example
+14.6k Golang : Read a file line by line
+4.3k PHP : Fix Call to undefined function curl_init() error
+8.4k Golang : Copy map(hash table) example
+10.6k Golang : Perform sanity checks on filename example
+7.2k Swift : Convert (cast) Character to Integer?
+6.1k Golang : Validate credit card example
+22.6k Golang : Daemonizing a simple web server process example
+9.9k Golang : Concatenate (combine) buffer data example
+15.3k Golang : read gzipped http response