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
+6.1k Linux/MacOSX : Search for files by filename and extension with find command
+11.6k Use systeminfo to find out installed Windows Hotfix(s) or updates
+4.4k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+7.2k Nginx : How to block user agent ?
+12.3k Golang : Split strings into command line arguments
+12.3k Golang : Pagination with go-paginator configuration example
+6.1k Fontello : How to load and use fonts?
+12.9k Swift : Convert (cast) Int or int32 value to CGFloat
+21.6k Curl usage examples with Golang
+26.9k Golang : Convert file content into array of bytes
+6.1k Golang : Extract unicode string from another unicode string example