Shuffle an array of objects - Javascript

Shuffle an array of objects – Javascript

0
(0)

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.

How useful was this post

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post





Leave a Reply

Please disable your adblocker or whitelist this site!