Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a recursive array [closed]


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?

like image 667
Inbar Azulay Avatar asked Sep 06 '25 10:09

Inbar Azulay


2 Answers

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!

like image 188
Nate Vaughan Avatar answered Sep 09 '25 05:09

Nate Vaughan


I am not sure, but what you have presented looks more like an object. In such case it is quite easy to traverse through the nested object, eg.

var object = { 0: "1",
1: {
    0: "2",
    1: {
        0: "3"
    },
    2: {
        0: "4",
        1: {
            0: "5"
        }
    }
}};

console.info(object);

function traverse(obj) {
  obj.keys.forEach(function(key) {
    if (typeof(obj[key]) === 'object') {
      traverse(obj[key])
    } 
      else {
        //do something with the actual value
        console.log(obj[key])
      }
    })      
};

traverse(object)

Can you specify what did you mean with I want the output to be the path of all the values?

like image 35
MatFiz Avatar answered Sep 09 '25 06:09

MatFiz