Skip to content

Instantly share code, notes, and snippets.

@ilyaviache
Last active February 19, 2017 11:48
Show Gist options
  • Save ilyaviache/24f8b62137a5d182b34c33e400a1103e to your computer and use it in GitHub Desktop.
Save ilyaviache/24f8b62137a5d182b34c33e400a1103e to your computer and use it in GitHub Desktop.
Transform flat array into tree view. Wrapped in Angular2 pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'tree' })
export class TreePipe implements PipeTransform {
transform(arr, args?: any[]) {
return this.buildTree(arr)
}
buildTree(elements, tree = []) {
elements.forEach((element) => {
if(!element.parent){
element.children = this.getNestedChildren(elements, element._id)
tree.push(element)
}
})
return tree;
}
getNestedChildren(elements, parent) {
let out = []
elements.forEach((element) => {
if(element.parent == parent){
let children = this.getNestedChildren(elements, element._id)
if(children.length > 0){ element.children = children; }
out.push(element)
}
})
return out
}
}
@ilyaviache
Copy link
Author

Expected input:
[ { id: 1 },{ id: 2 parent: 1 },{id: 3, parent: 1 }, {id: 4, parent: 2} ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment