Skip to content

Shuffle Array JavaScript | Simple example code

  • by

The simplest way to shuffle an array in JavaScript is to provide a custom function to a .sort().

array.sort((a, b) => 0.5 - Math.random());

But the best way to shuffle an array and have a truly random distribution of items, you have to implement the Fisher-Yates algorithm.

const shuffleArray = array => {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}

Shuffle Array JavaScript Example

Complete HTML example codes:

Simple way

<!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>

Output:

Shuffle Array JavaScript

The Fisher-Yates algorithm

<!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:

shuffle an array in JavaScript

How to Shuffle an Array and Return a New One in JS

<!DOCTYPE html>
<html>
<body>
	
	<script>
		
		function shuffleArray(array) { 
			
			var copy = [].concat(array);
			copy.sort(function(){
				return 0.5 - Math.random();
			});
			console.log(copy);
		}

		var original = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
		shuffleArray(original);
		console.log(original);
	</script>

</body>
</html>

Output:

Shuffle an Array and Return a New One in JS

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

Your email address will not be published. Required fields are marked *