Skip to content Skip to sidebar Skip to footer

How To Improve This Function That Converts A Flat Array Into A Tree?

I have this function that converts a flat array to a tree based on a path property. This is my data : const input = [ {'name':'brussels_district_north','path':'Brussels/Bruss

Solution 1:

You could check if the index plus one is equal to the length of the splitted path and add name.

const
    input = [{ name: "brussels_district_north", path: "Brussels/Brussels CBD/North" }, { name: "brussels_district_louise", path: "Brussels/Brussels CBD/Louise" }, { name: "brussels_district_west", path: "Brussels/Brussels Decentralised/West" }, { name: "brussels_district_léopold", path: "Brussels/Brussels CBD/Léopold" }, { name: "brussels_district_airport", path: "Brussels/Brussels Periphery/Airport" }, { name: "brussels_district_ring", path: "Brussels/Brussels Periphery/Ring" }, { name: "brussels_district_walloon-brabant", path: "Brussels/Brussels Decentralised/Walloon Brabant" }, { name: "brussels_district_centrum", path: "Brussels/Brussels CBD/Centre" }, { name: "brussels_district_midi", path: "Brussels/Brussels CBD/Midi" }, { name: "brussels_district_south", path: "Brussels/Brussels Decentralised/South" }, { name: "brussels_district_ north_east", path: "Brussels/Brussels Decentralised/North East" }],
    output = [];

input.reduce((r, item) => {
    item.path.split(/(?=\/)/).reduce((o, _, i, p) => {
        o.children = o.children || [];
        var path = p.slice(0, i + 1).join('');
        var temp = o.children.find(o => o.path === path);
        if (!temp) {
            o.children.push(temp = { path });
            if (i + 1 === p.length) temp.name = item.name;
        }
        return temp;
    }, r);
    return r;
}, { children: output });

console.log(output);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Post a Comment for "How To Improve This Function That Converts A Flat Array Into A Tree?"