What I need is to remove first word from the string again and again until only one word is left, and put it all into array.
For example, I have this string as an input:
Chicago IL 12345 United States
What I need to achieve is this array:
[ 'Chicago IL 12345 United States',
'IL 12345 United States',
'12345 United States',
'United States',
'States' ]
My code works but I wanted to get rid of the second param, and maybe make the code shorter and look more beautiful.
Here is what I currently have:
const stringToArray = (str, arr) => {
const result = arr || [];
const wordArray = str.split(' ');
const len = wordArray.length;
result.push(str);
if (len === 1) {
return arr;
}
return stringToArray(wordArray.slice((-1 * len) + 1).join(' '), result);
};
const partsArray = stringToArray('Chicago IL 12345 United States');
console.log(partsArray);