Inbar Azulay Inbar Azulay - 15 days ago 6
Javascript Question

Looping through a recursive array



I've got a recursive array. So the array below can go deeper and deeper.

0: "1"
1: [
0: "2"
1: [
0: "3"
]
2: [
0: "4"
1: [
0: "5"
]
]
]


I want the output to be the path of all the values. So 123 and 1245.

How can this be done in a Javascript method?

Answer

You need a recursive method to flatten a recursive array.

Here's a pretty basic one:

var data = ["1",
[
    "2",
    [
        "3"
    ],
    [
        "4",
        [
            "5"
        ]
    ]
]];

var flattened = [];

function flatten(data, outputArray) {
    data.forEach(function (element){
        if(Array.isArray(element)) {
            flatten(element, outputArray);
        } else {
            outputArray.push(element);
        }
    });
}

flatten(data, flattened);

This should get you moving in the right direction. Good luck!