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
+5.7k Unix/Linux : How to open tar.gz file ?
+3.4k Golang : Switch Redis database redis.NewClient
+15.4k Golang : Get checkbox or extract multipart form data value example
+23.4k Find and replace a character in a string in Go
+5.6k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+16.8k Golang : Covert map/slice/array to JSON or XML format
+13.1k Golang : error parsing regexp: invalid or unsupported Perl syntax
+4.8k Linux : How to set root password in Linux Mint
+39.8k Golang : Convert to io.ReadSeeker type
+7.6k Setting $GOPATH environment variable for Unix/Linux and Windows
+9.5k Golang : Format strings to SEO friendly URL example