1

I have a javascript list in the form of:

var list = [{id:1, data: "string", list: [
              {id:2, data: "string", list: [
                {id:3, data: "string", list: null}]},
              {id:4, data: "string", list: null}]}];

And I want it to be in the form of:

var list = [{id:1, data: "string", list: \\ original nested list or null, I don't care},
            {id:2, data: "string", list:},
            {id:3, data: "string", list:},
            {id:4, data: "string", list:}];

I have access to underscore.js, but I haven't been able to produce the output I want. I tried using a combination of _.flatten and _.pluck to get the underlying list, but I also need the id property so this doesn't work. My guess is that I need to map a function, but I'm kind of lost on the issue right now.

Could anybody help me with this?

1
  • 1
    like this? Commented Feb 22, 2016 at 18:45

1 Answer 1

4

You can use recursion to do it:

function flatten(arr) {
    if (!arr) {
        return [];
    }
    return arr.reduce(function (r, i) {
        return r.concat([i]).concat(flatten(i.list));
    }, []);
}

console.log(flatten(list));

With ES6 syntax (arrow functions and spread operator) it could look like this:

function flatten(arr) {
    return arr ? arr.reduce((r, i) => [...r, i, ...flatten(i.list)], []) : [];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is exactly what I wanted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.