// Shuffle array contents in place using Fisher-Yates shuffle algorithm - Code from Stack Overflow answer
// @param {Array} arr - An array containing items to be shuffled
function shuffle(arr) {
// counter == number of elements in arr
let counter = arr.length;
// while elements in arr remain unswapped
while (counter > 0) {
// get random idx value to pick element from arr
let idx = Math.floor(Math.random() * counter);
// Decrease counter
counter--;
// swap last element in array with randomly selected idx element
let temp = arr[counter];
arr[counter] = arr[idx];
arr[idx] = temp;
// console.log(`Loop: ${counter}, Index: ${idx}, Counter Element: ${arr[counter]}, Swap Index: ${arr[idx]}`);
}
return arr;
}
shuffle([1, 5, 6, 8, 2, 3, 5]);
// >>> [5, 8, 3, 2, 6, 1, 5]
// as always, this can be assigned to a variable i.e. let shuffledArray = shuffle([1, 2, 3, 4, 5, 6]);