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
+21.2k Golang : Convert Unix timestamp to UTC timestamp
+9.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+19.8k Golang : Get password from console input without echo or masked
+9.4k Golang : ISO8601 Duration Parser example
+5k Linux/MacOSX : Search for files by filename and extension with find command
+13.5k Golang : Execute function at intervals or after some delay
+34k Golang : How to split or chunking a file to smaller pieces?
+5k Golang : Calculate US Dollar Index (DXY)
+14.8k Golang : Delete files by extension
+5.3k Golang : Map within a map example
+11k Golang : 2 dimensional array example
+8.1k Random number generation with crypto/rand in Go