Skip to content Skip to sidebar Skip to footer

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

Solution 1:

You could take Array#flatMap with object flat children.

constflat = ({ 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; }

Solution 2:

constflat = arr => arr.concat(arr.flatMap(it =>flat(it.children)));

Post a Comment for "Generify Transformation Of Hierarchical Array Into A Flat Array"