I have a data array, I want to sum the whole commentId with JavaScript.
const comments = [
{
commentId: 1,
commentContent: 'Hai',
replies: [
{
commentId: 11,
commentContent: 'Hai juga',
replies: [
{
commentId: 111,
commentContent: 'Haai juga hai jugaa'
},
{
commentId: 112,
commentContent: 'Haai juga hai jugaa'
}
]
},
{
commentId: 12,
commentContent: 'Hai juga',
replies: [
{
commentId: 121,
commentContent: 'Haai juga hai jugaa'
}
]
}
]
},
{
commentId: 2,
commentContent: 'Halooo'
}
]
For example : Suppose there is commentId [1, 2, 11, 12, 111, 112, 121]. Hence, commentId.length is 7
You need to do this through recursive function. As there can be n level of nesting between comment and replies. Have a look at the following code.
function caluclateLength(commentsOrReplies, sum=0) {
sum += commentsOrReplies.length
return commentsOrReplies.reduce((total, commentorReply) => (total + caluclateLength(commentorReply.replies || [])), sum)
}
console.log(comments) // should return desired result