Question Description: Permission to ask, How do I create a function to calculate the total comments that exist, including all comment replies. Based on the data below using javascript, the total comments are 7 comments.

const comments = [
{
commentId: 1,
commentContent: 'Cry',
replies: [
{
commentId: 11,
commentContent: 'Cry too',
replies: [
{
commentId: 111,
commentContent: 'Cry too Cry too'
},
{
commentId: 112,
commentContent: 'Cry too Cry too Cry'
}
]
},
{
commentId: 12,
commentContent: 'Cry too',
replies: [
{
commentId: 121,
commentContent: 'Cry too Cry too'
}
]
}
]
},
{
commentId: 2,
commentContent: 'Cry'
}
]
Something like this should do it
const countComments = (data) => data.reduce((res, d) => {
if(!d.replies){
return res + d.commentContent.length
}
return res + d.commentContent.length + countComments(d.replies)
}, 0)
const comments = [{
commentId: 1,
commentContent: 'Cry',
replies: [{
commentId: 11,
commentContent: 'Cry too',
replies: [{
commentId: 111,
commentContent: 'Cry too Cry too'
},
{
commentId: 112,
commentContent: 'Cry too Cry too Cry'
}
]
},
{
commentId: 12,
commentContent: 'Cry too',
replies: [{
commentId: 121,
commentContent: 'Cry too Cry too'
}]
}
]
},
{
commentId: 2,
commentContent: 'Cry'
}
]
console.log(countComments(comments))