I am writing a function which accepts an array as a parameter. The function should then shuffle the array. If a particular condition is met (validMoveCounter <4) the function will create a new array from the cards available before shuffling. Otherwise, the function will just shuffle the array it is given.
The problem I am having is that when the else statement of my function runs the array is changed globally which is good. However when the main if a portion of my function runs I get an output with a shuffled array, but the array is not shuffled if I try and call it later in my program.
In other words, the else portion of my function changes the array globally, but the if portion of the function only changes the array locally.
function shuffle(array) {
if (validMoveCounter < 4) { //When no moves are left we need to reshuffle
array = [];
holder = []; //the holder will make an array of arrays which we will map into a 1d array
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 13; j++) {
if (board[i][j] !== board[i][j + 1] - 1) { //checks if two cards are consecutive in value
holder[i] = board[i].splice(j + 1, 12 - j + 1);
break;
}
}
}
console.log(holder);
for (let i = 0; i < 4; i++) {. // pushes the elements of holder into the 1d array
for(num of holder[i]) {
array.push(num);
}
}
for (let i = 0; i < array.length; i++) { // removes blanks from the deck
if (array[i] === 'X') {
array.splice(i, 1);
i--;
}
}
for (i = 0; i < array.length; i++) { //this is not changing the global deck!!
let p = array[i];
let j = Math.floor(Math.random() * array.length);
array[i] = array[j];
array[j] = p;
};
console.log(array);
} else {
for (i = 0; i < array.length; i++) {
let p = array[i];
let j = Math.floor(Math.random() * array.length);
array[i] = array[j];
array[j] = p;
};
console.log(array);
}
}