Shuffle an array of objects – Javascript

To shuffle an array of objects or single values in Javascript, use the following function:

for (var a = 0; a < data.length; a++) {
	var x = data[a];
	var y = Math.floor(Math.random() * (a + 1));
	data[a] = data[y];
	data[y] = x;
}

First, we are looping through all array elements. data is our array of objects. First, we are saving the current array element in a separate variable named x. Then we are generating a random number. Math.random() will return a random number between 0.0 and 0.9. As our loop start from 0, so we are multiplying that random number by loop iteration number + 1. Since the number will be in floating points, so we can convert that into an integer by calling Math.floor() function. The floor function will round the number downwards and return it as an integer. That is now the index of the random element in the array.

Then we are replacing the current array element with this random array element. And finally, replace this random array element with the current element of loop.

This is the simplest way to shuffle an array of objects using vanilla Javascript. For more Javascript tutorials, please follow here.