Randomize an array in JavaScript

Written by
Published on

Randomizing arrays can be helpful in various situations such as shuffling a deck of cards or when you just need a unique dataset for testing purposes.

I recently used it create the new typing tests on this site, in order to create a unique test each time. And here is the method that I used.

Let's take the following array as an example.

var list = [4, 5, 6, 20, 42, 2];

Randomizing the values comes down to swapping 2 of the elements at a time over and over, typically thousands of times. You can set up a for loop to run a high number of iterations for this.

for (let i = 0; i < 5000; i++){
    // randomize
}

Which 2 values will you be swapping? For that, you can use JavaScripts built in Math.random() method which returns a random number from 0 to 1. An example output would be the following:

You'll need to convert this random output to a whole number before you can use it.

You can do that by multiplying the Math.random() result by whatever number you want, which will become the max. The result will still be in decimal format, which is why I wrapped the entire thing in a Math.floor() .

let max = 50;
let random = Math.floor(Math.random() * max);

In our case, we want the maximum value to be the length of the array that is being shuffled.

let max = list.length;

We'll need two random locations for this swap to work. So back to the for loop. The first thing we'll do is to create 2 random numbers using the method above. We will then store the value in the first random location into a temporary variable and then swap the values in random location 2 with random location 1.

This will pretty much get rid of the value stored in the first location, which is why we kept it in a temporary variable.

The implementation looks like the following:

function randomize(list){
for(let i = 0; i < 5000; i++){
    let rand1 = Math.floor(Math.random() * list.length);
    let rand2 = Math.floor(Math.random() * list.length); 

    // now we can swap the values in these 2 locations
    // but first, create a temporary variable and store the values of the first random location 

    let tmp = list[rand1]; 

    // next up, copy the value in the second random location over to the first
    list[rand1] = list[rand2]; 

    // and now set the value of the second location to the temporary variable
    list[rand2] = tmp;
}
}

Last note. This will change the original array. And if that is something that you don't want to do, then you might want to change the randomize() function so that it creates and returns a cloned array instead.

Leave a comment

No messages posted yet

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post