Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
array
communitycreator

How to shuffle an array in JavaScript

Programming Bytes

Shuffle an array

Let’s write a shuffle function to randomly reorder elements of the array. For this, we will:

  • Loop through all elements of the array one by one
  • Generate a random index with Math.random()will return a random floating-point number between 0 and 1.
  • Swap the currentIndex element with generated random index.

Function to shuffle array

function shuffleArray(array) {
    let len = array.length,
        currentIndex;
    for (currentIndex = len - 1; currentIndex > 0; currentIndex--) {
        let randIndex = Math.floor(Math.random() * (currentIndex + 1) );
        var temp = array[currentIndex];
        array[currentIndex] = array[randIndex];
        array[randIndex] = temp;
    }
}
let a = [1,2,3,4,5];
console.log("Array before Shuffling", a);

console.log("Shuffling array");
shuffleArray(a);

console.log("Array after Shuffling", a);

In the code above we generate a random index using Math.random() * (curentIndex + 1). This will give a random index between 0(included) and currentIndex+1(excluded). In our case, if the currentIndex = 4, upon executing Math.random() * (curentIndex + 1), we will get a random number between 0(included) - 5(excluded) (i.e., any one from this number 0,1,2,3,4).


The code above will shuffle the elements in the original array. If you don’t want to shuffle the original array, make a clone of the original array and pass the cloned array to the shuffle function.

You can clone an array using array.slice(0).

function shuffleArray(array) {
    let len = array.length,
        currentIndex;
    for (currentIndex = len - 1; currentIndex > 0; currentIndex--) {
        let randIndex = Math.floor(Math.random() * (currentIndex + 1) );
        var temp = array[currentIndex];
        array[currentIndex] = array[randIndex];
        array[randIndex] = temp;
    }
}

let a = [1,2,3,4,5];
// clone using slice method  
let clonedArray = a.slice(0);

console.log("cloned array before shufflling " ,clonedArray); 

shuffleArray(clonedArray);
console.log("cloned array after shufflling " ,clonedArray); 

console.log("source array after shuffling" ,a); 

RELATED TAGS

javascript
array
communitycreator
RELATED COURSES

View all Courses

Keep Exploring