Last active
November 8, 2017 09:33
-
-
Save prrraveen/3404b4ee381c346210aede199fa1ee98 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const categories =[ { id: 'E-commerce', parent: null }, { id: 'Electronics', parent: 'E-commerce' }, { id: 'Mobiles', parent: 'Electronics' }, { id: 'Laptops', parent: 'Electronics' }, { id: 'Camera', parent: 'Electronics' }, { id: 'Lifestyle', parent: 'E-commerce' }, { id: 'Clothing', parent: 'Lifestyle' }, { id: 'Footware', parent: 'Lifestyle' }, { id: 'Grooming', parent: 'Lifestyle' }, { id: 'Jewellery', parent: 'Lifestyle' },] | |
| function Node(data) { | |
| this.data = data; | |
| this.children = []; | |
| } | |
| function solution(arr) { | |
| const n = arr.length | |
| if (n === 0) { | |
| return {} | |
| } | |
| const visited = Array(n).fill(false); | |
| const nullObjIndex = arr.findIndex( (o) => o.parent === null ); | |
| visited[nullObjIndex] = true | |
| const nullObj = arr[nullObjIndex] | |
| var root = new Node(nullObj.id) | |
| buildTree(root, arr, visited) | |
| console.log(root) | |
| var result = {} | |
| result[root.data] = {} | |
| buildObject(root, result[root.data]); | |
| return result; | |
| } | |
| function buildTree(curr, arr, visited) { | |
| if (visited.reduce( (a,b) => a && b)) { | |
| return | |
| } | |
| for(let i = 0; i < arr.length; i++) { | |
| if(curr.data === arr[i].parent) { | |
| curr.children.push( new Node(arr[i].id) ) | |
| visited[i] = true | |
| } | |
| } | |
| curr.children.map((child) => buildTree(child, arr, visited)) | |
| } | |
| function buildObject(currNode, currObj) { | |
| currNode.children.forEach((child) => { | |
| currObj[child.data] = {} | |
| buildObject(child, currObj[child.data]) | |
| }) | |
| } | |
| console.log(solution(categories)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment