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.3k Golang : Experimental Jawi programming language
+16.7k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+21.8k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+4.2k Javascript : Empty an array example
+13.5k Golang : Verify token from Google Authenticator App
+13.6k Golang : How to get year, month and day?
+9k Golang : Accept any number of function arguments with three dots(...)
+11.4k Golang : How to use if, eq and print properly in html template
+28.7k Get file path of temporary file in Go
+27.5k Golang : Convert CSV data to JSON format and save to file
+6.2k Golang : Missing Subversion command
+41.5k Golang : Convert string to array/slice