I'm trying to code a recursive function but I'm struggling and I was hoping someone could help push me in the right direction. I believe that this would be considered "Tree Recursion".
This is a trivial example to illustrate the data and what I'm trying to do. Obviously, the real data is more complex...
Basically, I start with an array containing a single array of objects like below where prop2 in any of the objects can either be a valid string or an empty string...
[
[
{ prop1: "abc", prop2: "" },
{ prop1: "def", prop2: "one" },
{ prop1: "ghi", prop2: "" }
]
]
My algorithm needs to look at the array above and iterate over the objects. As soon as it encounters an object with an empty string in prop2, it needs to clone the array three times and replace the empty string in that object (and only that object) with three different values (one/two/three) like this...
[
[
{ prop1: "abc", prop2: "one" },
{ prop1: "def", prop2: "one" },
{ prop1: "ghi", prop2: "" }
],
[
{ prop1: "abc", prop2: "two" },
{ prop1: "def", prop2: "one" },
{ prop1: "ghi", prop2: "" }
],
[
{ prop1: "abc", prop2: "three" },
{ prop1: "def", prop2: "one" },
{ prop1: "ghi", prop2: "" }
]
]
Then the algorithm starts again, except that the the input is this new array containing three arrays.
So on the second iteration, each of the three arrays will get cloned three times and the empty string will get replaced in the same way.
The end result for this simple example would be an array of nine arrays.
If the array had more objects with empty prop2 values, there would be more iterations.
Basically, I'm taking an array of objects where some of the props are empty strings and "expanding" that particular prop value to every permutation of "one"/"two"/"three"
I know that this is an ideal problem for recursion but I'm having trouble figuring out the code.
I think that the "base case" would probably be where I have an array of objects and none of the objects have properties with empty strings. That case would return that array.
I don't know what the other case would look like other than calling the same function three times with the three newly created variants. I also don't know what this case should be returning.
I'm having trouble finding reference examples online that are similar to what I'm trying to do.
EDIT: Looking at the recursive responses, even though they all do work, it's obvious that a recursive solution wasn't as straightforward as I thought it would be. The non-recursive answer is actually the best answer.