This post will discuss how to randomly shuffle an array in JavaScript.

Shuffling an array in JavaScript means rearranging the elements of the array in a random order. Here are some examples of how to shuffle an array in JavaScript given an array:

1. Using Fisher-Yates shuffle algorithm

The Fisher-Yates shuffle algorithm is a classic and unbiased algorithm for generating a random permutation of a finite sequence. The algorithm works by iterating over the array from the last element to the first element, and swapping each element with a random element from the remaining part of the array. For example, to shuffle an array of numbers, we can use the following code:

Download  Run Code

 
This algorithm is considered the de-facto standard for shuffling arrays in JavaScript.

2. Using sort() function

This is another technique that works in any version of JavaScript. It involves using the sort() function on the array object, which sorts the elements of the array in place and returns the sorted array. By passing a custom compare function to the sort() function, we can shuffle the elements randomly. The compare function should return a negative, zero, or positive value, depending on whether the first element is less than, equal to, or greater than the second element. Here’s an example:

Download  Run Code

 
The code uses the sort() function with a function as an argument. The function returns a random value between -0.5 and 0.5, which will determine whether to swap or keep the elements of the array. This technique is simple and concise, but it is not very efficient or reliable.

That’s all about randomly shuffling an array in JavaScript.