A
A
Alexander2020-09-19 19:16:17
JavaScript
Alexander, 2020-09-19 19:16:17

Add a function to create a response tree?

I am developing a frontend for a self-written forum. You need to write a function that will create a tree of responses in posts. This tree will then be recursively rendered by React (this is already done).
A typical post looks like this (removed elements that are not related to the task):

{
    id: 2,
    refTo: 1
    comment: 'Комментарий'
}

id - the id of the post, refTo - the id of the post this post replies to.

Wrote the following function:
const createReplyTree = (replyNode, thread = replyNode) => {
        const tree = replyNode.map(i => {
            const replies = thread.filter(item => item.refTo === i.id);
            return {...i, replies: createReplyTree(replies, thread)};
        });
        return tree;
    };

Partially implements the task - to the posts to which someone answered, these posts are recursively added to replies. But there are duplicate answers left at the end of the array. They need to somehow be excluded from the array.
The solution is desirable in ES6 and without third-party libraries.

Posts may or may not have a refTo.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-09-19
@dimoff66

Iterating over an array with filtering will only work fast with a small number of elements, or when using memo or reselect, to ensure speed it is better to translate the array into a tree. Something like this.

const toTree = (arr, idAttr = 'id', parentAttr = 'parentId') => {
  arr.sort((a, b) => 
    (a[parentAttr] === b[idAttr] && 1) ||
    (b[parentAttr] === a[idAttr] && -1) ||
    0)

  const tree = arr.reduce((tree, data) => {
    data.children = []
    tree[data[idAttr]] = data;
    (tree[data[parentId]] || tree).children.push(data);
    return tree
  }, { children: [] }).children;

  return tree
}

Get a tree in the form
[{
    id: 1,
    comment: 'Комментарий',
    children: [{
        id: 2,
        refTo: 1.
        children: ...  
    }, {
        id: 3.
        refTo: 1,
    }]
}, {...}]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question