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.4k Javascript : How to loop over and parse JSON data?
+10.2k Golang : Text file editor (accept input from screen and save to file)
+11.8k Golang : How to detect a server/machine network interface capabilities?
+8.9k Golang : Sort lines of text example
+10.5k Swift : Convert (cast) String to Integer
+5.4k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+11.1k Golang : Create S3 bucket with official aws-sdk-go package
+6.9k Golang : Decode XML data from RSS feed
+15.3k Golang : How to check if IP address is in range
+8.1k Golang : Handle Palindrome string with case sensitivity and unicode