Is there a way for this function to return this array? If I console log the output, I do see that this array appears but then there are 3 undefineds, and I don’t understand why they are occurring.
[‘Queen of Diamonds’,
‘Jack of Hearts’,
‘Five of Hearts’,
‘Ten of Spades’,
‘Ace of Spades’,
‘Eight of Clubs’,
]
function shuffle(topHalf, bottomHalf, i = 0, newArr = []) { //add index
// base case: no element in topHalf and no element in bottomhalf
//- based on the index of both arrays, then return newArr
if (i >= topHalf.length && i >= bottomHalf.length) {
// console.log('return')
//console.log(newArr);
console.log("I run once");
return newArr;
}
//if there is an element in tophalf and bottomhalf: push toph, then bottomh arrays
if (topHalf[i] && bottomHalf[i]) {
console.log("I run twice for both");
newArr.push(topHalf[i]);
newArr.push(bottomHalf[i]);
} //if there is an element in tophalf but not in bottomhalf, push tophalf
else if (topHalf[i]) {
newArr.push(topHalf[i]);
console.log("I run twice for tophalf only");
//console.log(newArr)
//console.log("topHalf")
}//if there is an element in bottomhalf, but not in tophalf, push bottomhalf
else if (bottomHalf[i]) {
console.log("I do NOT run at all");
newArr.push(bottomHalf[i]);
}
//recursive call, index increments
return shuffle(topHalf, bottomHalf, i+=1, newArr);
}
// UNCOMMENT TO TEST YOUR WORK
const topHalf = ['Queen of Diamonds', 'Five of Hearts', 'Ace of Spades', 'Eight of Clubs']
const bottomHalf = ['Jack of Hearts', 'Ten of Spades']
shuffle(topHalf, bottomHalf);
// /*-> ['Queen of Diamonds',
// 'Jack of Hearts',
// 'Five of Hearts',
// 'Ten of Spades',
// 'Ace of Spades',
// 'Eight of Clubs',
// ]
// */