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 :

function createArr(str) {

let results = [];
if (str.length === 0) { 
return results; 
}

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

else { 
var letters = createArr(str.slice(str.length-1)) 
results.push(letters);
return results;
}
}

console.log(createArr('Hello'));

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

Thanks in advance! 🙂

Answer

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

function createArr(str) {
  if(!str.length) return []; // return an empty array when the string is empty
  
  return [
    str[0], // take the current letter
    ...createArr(str.slice(1)) // pass the rest of the string to createArr
  ]
}

console.log(createArr('Hello'));


Source: stackoverflow