# How to shuffle an array in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published May 16, 2020. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-shuffle-array

> A quick hack to learn how to randomize or shuffle an array in vanilla JavaScript.

In vanilla JavaScript, there is no direct way to randomize array elements. Although languages like PHP and Ruby provide built-in methods for shuffling arrays, JavaScript does not.

The most commonly used solution to randomize an array is the [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) algorithm:

> 1. Write down the numbers from 1 through N.
> 2. Pick a random number k between one and the number of unstruck numbers remaining (inclusive).
> 3. Counting from the low end, strike out the kth number not yet struck out, and write it down at the end of a separate list.
> 4. Repeat from step 2 until all the numbers have been struck out.
> 5. The sequence of numbers written down in step 3 is now a random permutation of the original numbers.

Here is a JavaScript function that implements the Fisher-Yates shuffle algorithm:

```javascript
const shuffle = (array) => {

    // loop all elements
    for (let i = array.length - 1; i > 0; i--) {

        // pickup a random element
        const j = Math.floor(Math.random() * i);
        const temp = array[i];

        // swap it with the current element
        array[i] = array[j];
        array[j] = temp;
    }
};
```

Now you can call the above function by passing in the array as an argument:

```javascript
const fruits = ['?', '?', '?', '?', '?'];

// shuffle array
shuffle(fruits);

console.log(fruits);

// [ '?', '?', '?', '?', '?' ]
```

The above solution shuffles the original array and does not return a copy. If you want to keep the original array unchanged, use the `Array.slice()` method to pass in a copy:

```javascript
const fruits2 = fruits.slice();

shuffle(fruits2);
```

If you are already using [Lodash](https://lodash.com/docs/4.17.15#shuffle) in your project, just use the `_.shuffle()` method to randomize an array. This method implements the same Fisher-Yates shuffle algorithm to shuffle array elements, and returns a new array:

```javascript
const _ = require('lodash');

const fruits = ['?', '?', '?', '?', '?'];

// shuffle array
const shuffled = _.shuffle(fruits);

console.log(shuffled);

// [ '?', '?', '?', '?', '?' ]
```

Take a look [this guide](https://attacomsian.com/blog/javascript-arrays) to learn more about JavaScript arrays and how to use them to store multiple values in a single variable.
