Rus
Eng
Сортировка списка комментариев Wordpress для получения древовидного списка на ES6

All English-language materials have been translated fully automatically using the Google service

Wordpress is a great CMS, but I had to struggle to sort the comments in a tree-like order. Thanks to Kobe on stackoverflow for the awesome ES6 sorting feature

We have an array as input

Unsorted array of comments

We transform it using the function:

  var comments = this.props.data.COMMENTS;

comments = comments.sort ((a, b) => b.comment_parent - a.comment_parent);

const sortComments = (comments) => {
var temp = [... comments];

comments.forEach ((o, index) => {
if (temp [0] .comment_parent === 0) {return;}
var parentIndex = temp.findIndex (o => o.comment_ID === temp [0] .comment_parent);

if (typeof temp [parentIndex]! = "undefined") {
temp [parentIndex] .children? temp [parentIndex] .children.push (temp [0]): temp [parentIndex] .children = [temp [0]];
temp.shift ();
}


});

return temp;
}  

And we get the output:

Sorted array of comments

To display comments recursively, you can use example 0xD34F with qna.habr.com

Repost material:

Comments

There are no comments yet, you can be the first to leave it

Leave a comment

The site uses a comment pre-moderation system, so your message will be published only after approval by the moderator

You are replying to a user's comment

Send

FEEDBACK

Email me

Are you developing a new service, making improvements to the existing one and want to be better than your competitors? You have come to the right place. I offer you a comprehensive studio-level website development. From me you can order design, layout, programming, development of non-traditional functionality, implementation of communication between CMS, CRM and Data Analitics, as well as everything else related to sites, except for promotion.

Contact, I will always advise on all questions and help you find the most effective solution for your business. I am engaged in the creation of sites in Novosibirsk and in other regions of Russia, I also work with the CIS countries. You will be satisfied with our cooperation

An error occurred while sending, please try again after a while
Message sent successfully

Phones

+7(993) 007-18-96

Email

info@tichiy.ru

Address

Россия, г. Москва

By submitting the form, you automatically confirm that you have read and accept the Privacy Policy site

Contact with me
Send message
By submitting the form, you automatically confirm that you have read and accept Privacy policy of site
Sending successful!
Thank you for contacting :) I will contact you as soon as possible
Sending failed
An error occurred while sending the request. Please wait and try again after a while or call my phone number