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:

Complete example code:

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

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.

Output:

JavaScript Shuffle Array elements example

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

Note: 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.