let rootNode = listArray.filter(la => { return !la.parentId }).sort((a, b) => { return a.timestamp - b.timestamp }) let array = []; function getNode(node, level, arr) { node.level = level; arr.push(node); let ccnode = listArray.filter(la => { return la.parentId == node.id; }) level++; if (ccnode) { ccnode.sort((a, b) => { return a.timestamp - b.timestamp }).forEach(cnode => { debugger; getNode(cnode,level, arr); }) } } rootNode.forEach(rn => { getNode(rn, 1, array); })