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
+6k Golang : Measure execution time for a function
+5k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+5.7k Golang : Find change in a combination of coins example
+13.1k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+13.5k Android Studio : Password input and reveal password example
+36.3k Golang : Save image to PNG, JPEG or GIF format.
+20.6k Golang : Saving private and public key to files
+11.3k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+6k PHP : Get client IP address
+9.9k Golang : Channels and buffered channels examples
+4.7k Unix/Linux : How to pipe/save output of a command to file?