Skip to content

Instantly share code, notes, and snippets.

@adriaandotcom
Created November 18, 2018 17:00
Show Gist options
  • Save adriaandotcom/4a38a4f63b446e9de5d053051e12636c to your computer and use it in GitHub Desktop.
Save adriaandotcom/4a38a4f63b446e9de5d053051e12636c to your computer and use it in GitHub Desktop.
Write recusive function to read comments
const comments = [
{ id: 1, original_id: null, upvotes: 10, text: 'Hi..' },
{ id: 2, original_id: null, upvotes: 0, text: 'Je..' },
{ id: 3, original_id: 1, upvotes: 0, text: 'Di..' },
{ id: 4, original_id: 1, upvotes: 7, text: 'Si..' },
{ id: 5, original_id: 1, upvotes: 5, text: 'Op..' },
{ id: 6, original_id: null, upvotes: 2, text: 'Op..' },
{ id: 7, original_id: 6, upvotes: 2, text: 'Op..' },
{ id: 8, original_id: 5, upvotes: 3, text: 'Op..' },
{ id: 9, original_id: 1, upvotes: 3, text: 'Op..' }
]
function getChildren(original_id) {
return getComments(comments.filter(comment => comment.original_id === original_id))
}
function getComments(comments) {
const replies = []
for (const comment of comments) {
replies.push(getChildren(comment.id))
}
return replies
}
console.log(getComments(comments)) // output [ [ [], [], [ [] ], [] ], [], [], [], [ [] ], [ [] ], [], [], [] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment