3

I am trying to implement a user hierarchy using the js library orgChart. by getHierarchy() method in the library is outputting a object like the following.

var datascource = {
            "id": "1",
            "children": [{
                "id": "2"
            }, {
                "id": "3",
                "children": [{
                    "id": "4"
                }, {
                    "id": "5",
                    "children": [{
                        "id": "6"
                    }, {
                        "id": "7"
                    }]
                }]
            }, {
                "id": "10"
            }, {
                "id": "12"
            }]
        };

I want to generate flat array from ids in the tree. ex: //["1", "2", "3", "4", "5", "6", "7", "10", "12"]

I came up with,

function getNestedArraysOfIds(node) {
    if (node.children == undefined) {
        return [node.id];
    } else {
        return [node.id,...node.children.map(subnode => (subnode.children==undefined) ? subnode.id: getNestedArraysOfIds(subnode))];
    }
}

function getIds(array) {
        return array.reduce((acc, subArray) =>
            (Array.isArray(subArray)) ? [...acc, ...getIds(subArray)] : [...acc, subArray]);
    }

var idArrays = getNestedArraysOfIds(datascource );
var ids = getIds(idArrays); //["1", "2", "3", "4", "5", "6", "7", "10", "12"]

I have try to do it with single reduce function but I end up writing two functions both of them are recursive. Is there much elegant and effective way to do it with single reduce function?

Thank you in advance.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
Sankha Karunasekara
  • 1,636
  • 18
  • 19

3 Answers3

6

You could flat the children by taking a mapping with concat.

function getFlat({ id, children = [] }) {
    return [id].concat(...children.map(getFlat));
}

var data = { id: "1", children: [{ id: "2" }, { id: "3", children: [{ id: "4" }, { id: "5", children: [{ id: "6" }, { id: "7" }] }] }, { id: "10" }, { id: "12" }] };

console.log(getFlat(data));

Same with a reduce function

function getFlat({ id, children = [] }) {
    return children.reduce((r, o) => [...r, ...getFlat(o)], [id]);
}

var data = { id: "1", children: [{ id: "2" }, { id: "3", children: [{ id: "4" }, { id: "5", children: [{ id: "6" }, { id: "7" }] }] }, { id: "10" }, { id: "12" }] };

console.log(getFlat(data));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

Use a recursion with Array.flatMap() and spread to get the id and children's ids, and flatten to a single array:

const getIds = ({ id, children }) => children ? [id, ...children.flatMap(getIds)] : id;

const dataSource = {"id":"1","children":[{"id":"2"},{"id":"3","children":[{"id":"4"},{"id":"5","children":[{"id":"6"},{"id":"7"}]}]},{"id":"10"},{"id":"12"}]};

const result = getIds(dataSource);

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

You can create a simple recursive function & use for..in to iterate it. If the key is id then push the value of it to an array, else if the value of the key is an array , for example the value of children key is an array , then call the same recursive function inside a for loop and pass each object

let datascource = {
  "id": "1",
  "children": [{
    "id": "2"
  }, {
    "id": "3",
    "children": [{
      "id": "4"
    }, {
      "id": "5",
      "children": [{
        "id": "6"
      }, {
        "id": "7"
      }]
    }]
  }, {
    "id": "10"
  }, {
    "id": "12"
  }]
};

let data = [];

function flatData(obj) {
  for (let keys in obj) {
    if (keys === 'id') {
      data.push(obj[keys])
    } else if (Array.isArray(obj[keys])) {
      obj[keys].forEach((item) => {
        flatData(item)
      })

    }
  }
}
flatData(datascource)
console.log(data)
brk
  • 48,835
  • 10
  • 56
  • 78