Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Performatic list to tree using one loop and map
//+ Jonas Raoni Soares Silva
//@ http://raoni.org
function tree(items) {
const tree = [];
const map = new Map;
for (const item of items) {
const placeholder = map.get(item.id);
item.children = placeholder ? placeholder.children : [];
map.set(item.id, item);
//root condition
if (item.parentId === item.id) {
tree.push(item);
}
else {
const parent = map.get(item.parentId);
if (!parent) {
map.set(item.parentId, {children: [item]})
}
else {
parent.children.push(item);
}
}
}
return tree;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment