# Recursion Problem in Javascript

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’,
‘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',
//         'Eight of Clubs',
//       ]
//   */

``````

So push one from top half to a new array, push one from bottom to that array. When one half runs out, keep pushing from the remaining half until they’re all used up, then return the new array? The root of your problem looks to be that you’re not checking the length in the correct places. Here’s some pseudocode that cleans up the logic a bit:

``````function shuffle(topHalf, bottomHalf, shuffledDeck = []):
IF the length of both topHalf and bottomHalf is 0
return the shuffledDeck
ELSE
IF length of topHalf is > 0, slice off the first value
and push to the shuffledDeck
IF length of bottomHalf is > 0, slice off the first
value and push it to the shuffledDeck

return shuffle(topHalf, bottomHalf, shuffledDeck)
ENDIF``````

I see. So slicing is needed with the length going down to zero, rather than having an incrementing element.