Skip to content
Advertisement

Recursion question: Create array where each letter occupies an index of the array

I am using javascript.

I am new to recursive functions, and cannot seem to figure out how to express this logic recursively:

” Write a function that accepts a string and creates an array where each letter // occupies an index of the array. “

(Firstly,) I think the question is asking me to do the following:

‘Hello’ -> [‘H’, ‘e’, ‘l’, ‘l’, ‘o’];

It is simple enough, but nothing I try seems to be working. I thought the base call could be :

JavaScript

and then I would recursively return the last letters of the string, and push them out once the stack is returned, like so:

JavaScript

But for some reason nothing seems to be working .. I would really appreciate if someone could clarify this problem for me.

Thanks in advance! 🙂

Advertisement

Answer

You can use recursion with array spread, to create an array, and flatten the results to a single array:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement