Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Intoduction to functional programming in JS - Solutions
const buildTree = (list, parent) => {
var node = {}
list
.filter(x => x.parent === parent)
.forEach(x => {
node[x.id] = buildTree(list, x.id)
})
return node
}
// { autofold
module.exports = {
buildTree: buildTree
};
// }
@markusand

This comment has been minimized.

Copy link

markusand commented Jul 17, 2018

A pure functional version:

const buildTree = (list, parent) => {
	return list
	.filter(p => p.parent === parent)
	.reduce((children, child) => {
		children[child.id] = buildTree(list, child.id);
		return children;
	},{});
}
@NurbekGithub

This comment has been minimized.

Copy link

NurbekGithub commented Oct 1, 2019

How about this

const buildTree = (list, parent) => {
  return list.reduce((acc, curr) => {
    if (curr.parent === parent) {
      acc[curr.id] = buildTree(list, curr.id);
    }
    return acc;
  }, {});
}
@Aronja

This comment has been minimized.

Copy link

Aronja commented Oct 19, 2019

It also works with map:

const buildTree = (list, parent) => { 
    let familytree = {}
    list.filter(x => x.parent === parent)
        .map(x => {
            familytree[x.id] = buildTree(list, x.id)
         })
    return familytree
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.