var arr = [
{id: 7, post: 1, parent: 4, author: 1, author_name: 'me'},
{id: 6, post: 1, parent: 5, author: 1, author_name: 'me'},
{id: 5, post: 1, parent: 4, author: 1, author_name: 'me'},
{id: 4, post: 1, parent: 0, author: 1, author_name: 'me'},
{id: 3, post: 1, parent: 0, author: 1, author_name: 'me'},
{id: 2, post: 1, parent: 1, author: 1, author_name: 'me'},
{id: 1, post: 1, parent: 0, author: 0, author_name: 'other'},
]
arr = arr.sort((a, b) => b.parent - a.parent)
const sortComments = (arr) => {
var temp = [...arr]
arr.forEach((o, index) => {
if (temp[0].parent === 0) return
var parentIndex = temp.findIndex(o => o.id === temp[0].parent)
temp[parentIndex].children ? temp[parentIndex].children.push(temp[0]) : temp[parentIndex].children = [temp[0]]
temp.shift()
})
return temp
}
console.log(sortComments(arr))