Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generify transformation of hierarchical array into a flat array

I'm trying to generify the transformation of a hierarchical array into a flat array. I have this kind of object which has children of the same type, which has children of the same type etc..

[{
        id: "123",
        children: [
            {
                id: "603",
                children: [
                    {
                        id: "684",
                        children: [
                            ...
                        ]
                    },
                    {
                        id: "456",
                        children: []
                    }
                ]
            }
        ]
    }]

I found a way to flatten it and I have the information of the number of nested levels. One level deep (works):

let result = myArray.flat()
            .concat(myArray.flatMap(comm => comm.children));

Two levels deep (works):

 let result = myArray.flat()
            .concat(myArray.flatMap(comm => comm.children))
            .concat(myArray.flatMap(comm => comm.children.flatMap(comm2 => comm2.children)));

But how can I generify this code in a function to handle any deepness ? I already tried this but it does not work:

  flatFunct = (myArray, deep) => {
        let func = comm => comm.children;
        let flatMapResult = myArray.flat();
        for (let i = 0; i < deep; i++) {
            flatMapResult = flatMapResult.concat(() => {
                let result = myArray;
                for (let j = 0; j < i; j++) {
                   result = result.flatMap(func);
                }
            });
        }
    };

I'm close, but I don't find the way.

like image 462
Dotista Avatar asked Sep 05 '25 06:09

Dotista


2 Answers

You could take Array#flatMap with object flat children.

const
    flat = ({ children = [], ...o }) => [o, ...children.flatMap(flat)],
    data = [{ id: "123", children: [{ id: "603", children: [{ id: "684", children: [{ id: "688", children: [] }] }, { id: "456", children: [] }] }] }],
    result = data.flatMap(flat);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 124
Nina Scholz Avatar answered Sep 07 '25 21:09

Nina Scholz


const flat = arr => arr.concat(arr.flatMap(it => flat(it.children)));
like image 30
Jonas Wilms Avatar answered Sep 07 '25 19:09

Jonas Wilms