Shuffle an array in Javascript
Given an array, shuffle each element in the array and returns the shuffled array.
function shuffle(arr) { var arrSize = arr.length; // array size var randomIndex; var temp; // temperary variable for swapping purpose for(var i=arrSize-1; i>=0; i--) // Loop through the array from tail to head { randomIndex = Math.floor(Math.random()*i); // Get a random index from the remaining unprocessed index // These 3 lines are doing the swap temp = arr[i]; arr[i] = arr[randomIndex]; arr[randomIndex] = temp; } return arr; // Return the shuffled array }
Demo, Given array: 1,2,3.3,4,5,6,7 Shuffled array:
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts