OneBite.Dev - Coding blog in a bite size

shuffle the elements in an array in Javascript

Code snippet on how to shuffle the elements in an array in Javascript

  function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1)); // Generate a random index
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

The code above is a function that shuffles the elements of an array. It uses a ‘for loop’ to iterate over each element of the array. For each element, it generates a random index between 0 and the current index of the element. Then, it swaps the current element with the one at the random index, and stores the original element in a temporary variable. After the loop is done, all the elements in the array have been randomly changed, making the array shuffled. Finally, the shuffled array is returned.

javascript