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
+10.5k Golang : Handle API query by curl with Gorilla Queries example
+3.8k Which content-type(MIME type) to use for JSON data
+5.9k Golang : Mapping Iban to Dunging alphabets
+7.5k Golang : Gaussian blur on image and camera video feed examples
+11k Golang : Display list of countries and ISO codes
+6.5k Gogland : Single File versus Go Application Run Configurations
+11.7k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+40.6k Golang : Get hardware information such as disk, memory and CPU usage
+33.4k Golang : Upload and download file to/from AWS S3
+21.2k Golang : Round float to precision example
+10.6k Golang : Clean formatting/indenting or pretty print JSON result
+18.8k Golang : How to get struct tag and use field name to retrieve data?