I have a recursive function to work with nested arrays that are multi-level deep. The code below is supposed to select random elements, one from each level, and combine them into an array (in the order they are printed out in the console). However, the resulting array only contains elements of the highest levels (A, B or C, D or C), nothing below that. What is the reason for that?
const arry = [
["A"],
["B", "C"],
["D", "E"],
[
[
["F1", "F2"],
["G1", "G2"],
[
"H1",
"H2",
[
["I1", "I2", "I3"],
["J1", "J2"],
["K1", "K2", "K3"],
],
],
],
],
];
function rndmElementSelection(array) {
rndElm = array[Math.floor(Math.random() * array.length)];
return rndElm;
}
function recursion(array, resultAry = []) {
array.forEach((element) => {
if (typeof element === "string") {
console.log(element);
resultAry.push(element);
} else {
nE = rndmElementSelection(element);
if (typeof nE === "string") {
console.log(nE);
resultAry.push(nE);
} else {
recursion(nE);
}
}
});
return resultAry;
}
console.log(recursion(arry));
Is,Js, andKs are at the same level as theHstrings, you will get either anH(e.g.["A", "C", "D", "F2", "G1", "H2"]) or oneI, oneJ, and oneK(e.g.["A", "C", "E", "F2", "G1", "I3", "J1", "K2"]). Is this your intent?