JSFiddle - React, Tailwind, and code Playground

by BurpmanJunior

JavaScript

/**
 * Fisher-Yates Shuffling
 * https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
 */
function shuffle(arr){
    var i,    // index crawl
        j,    // random index
        temp; // swap value storage
    for(i = arr.length - 1; i > 0; i--){ // loop backwards through array to cut unnecessary passes
        j      = Math.floor(Math.random() * (i + 1)); // select random availble index. i + 1 for possible self selection
        temp   = arr[i]; // store self
        arr[i] = arr[j]; // overwrite with new value from random index
        arr[j] = temp; // restore self in swapped value location
        console.log('Swapped: '.concat([i,j]) + (i===j ? ' - self selected' : ''));
    }
    return arr;
};

console.clear();

var a = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(a);
var b = shuffle(a);
console.log(b);