I'm trying to write a RECURSIVE function that randomizes/shuffles an array.
The function I have written is using the Fisher-Yates shuffle method, which works fine on small arrays, but gives a 'Maximum call stack exceeded error' on my intended array containing 5000 elements
I wondered if someone could help me fix this method so that it still works recursively on larger arrays?
Here is the function below:
shuffleArray = (array, currentIndex=0) => {
if (currentIndex >= array.length) {
return array;
}
let randomIndex = Math.floor(Math.random() * currentIndex);
let tempValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = tempValue;
let newIndex = currentIndex += 1;
return this.shuffleArray(array, newIndex);
}
console.log(shuffleArray([1, 2, 3, 4, 5, 6]));
// returns a random array like [3,4,6,1,2,5]
console.log(shuffleArray([...Array(5000).keys()]));
// an example array of 5000 elements returns error: Uncaught RangeError: Maximum call stack size exceeded