JavaScript randomize array | Shuffle Array elements Example

You can shuffle Randomly arrange JavaScript by using a loop or array sort with the Math random method.

Array Shuffle means to remix the array elements, to have them in a different order than the previous one.

JavaScript randomize array Examples

Let’s see HTML example code for it:-

Multiple runs of shuffle may lead to different orders of elements.

Using sort() method

This is simple solution could be:

var check = function(){
    if(condition){
        // run when condition is met
    }
    else {
        setTimeout(check, 1000); // check again in a second
    }
}

check();

Complete example code:

Passing a function that returns (random value – 0.5 ) as a comparator to sort function, so as to sort elements on a random basis.

<!DOCTYPE html>
<html>
<body>
	
	<script>
		function shuffle(array) {
			array.sort(() => Math.random() - 0.5);
		}

		let arr = [1, 2, 3, 4, 5];
		shuffle(arr);
		alert(arr);
	</script>

</body>
</html>

Note: Calling sort() on a list does not change the original array value.

Output:

JavaScript randomize array example

Using for loop

This loop is responsible for going through every item in our array and swapping it with a random number.

<!DOCTYPE html>
<html>
<body>
	
	<script>
		
		function shuffleArray(array) { 
			for (var i = array.length - 1; i > 0; i--) {  

				var j = Math.floor(Math.random() * (i + 1)); 

				var temp = array[i]; 
				array[i] = array[j]; 
				array[j] = temp; 
			} 

			return array; 
		} 

		var arr = [1,2,3,4,5];
		console.log(shuffleArray(arr));

	</script>

</body>
</html>

Output:

JavaScript Shuffle Array elements example

Do comment if you have any doubts and suggestions on this JS array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.