javascript
Sort Tree - Bloomberg - Port Interactive Analytics - Front End - 12/6/21
// Let's assume you are given the world tree, wherein the first level represents continents, the second level represents countries, the third level represents states/provinces and so on. Write a method to re-arrange this tree in such a way that all children of every node are sorted in alphabetical order.
World
/
North America
/ \
US Canada
/ \ \
California NYC Alabama
Node {
value
children: Node[]
}
Tree {
topNode: Node
}
function sortChildren(tree) {
// Continents
tree.topNode.children.sort((childNode1, childNode2) => {
if (childNode1.value < childNode2.value) {
return -1;
} else (childNode1.value > childNode2.value) {
return 1;
}
return 0;
})
tree.topNode.children.foreach((continent) => {
continent.children.foreach((country) => {
country.children.foreach((state) => {
})
})
});
}
function sort(node) {
if (node.children) {
node.children.foreach(() => { sort(node)}))
} else {
// reached the end
}
}
Was this helpful?
Similar Posts
- Recommendations - Bloomberg - Port Interactive Analytics - Full Stack - 11/8/21
- Valid Dictonary String - Bloomberg - Port Interactive Analytics - Full Stack - 11/8/21
- Microsoft Fill Paint - Bloomberg - Port Interactive Analytics - Full Stack - 12/6/21
- Batched Requests - AirTable - Automations - Front End - 12/3/21
- Sort array using Array.sort() in javascript
- Remove new line separator from start and end positions of string in Javascript
- Lodash - Find item index from array by searching from the end