srvqaqa
srvqaqa

Reputation: 510

Output all nested array elements with recursion

So, let's consider we have such array:

let array = ["Alex", 1,2,["Marta", 3], [[5, "Melman"]], 6];

I want to output all its elements with recursive function. My function is as follows:

function recursive(arr){
    for(let f of arr){
        if(typeof(f)==="object"){
            return recursive(f);
        }
        else{
            return f;
        }
    }
}

But it doesn't work properly. So where is the problem ?

Upvotes: 0

Views: 92

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44105

You need to log the item to the console. And don't return from the if:

if (typeof f === "object") {
    recursive(f);
}

else {
    console.log(f);
}

(Also note that typeof is intended to be an operator, not a function.)

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386654

You end the function with the first return statement.

Instead, you could take a Generator and yield the items or the inner array by calling the function.

function* recursive (arr) {
    for (let f of arr) {
        if (Array.isArray(f)) yield* recursive(f);
        else yield f;
    }
}

let array = ["Alex", 1, 2, ["Marta", 3], [[5, "Melman"]], 6];

console.log(...recursive(array));

Upvotes: 0

Related Questions