Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
count all comment letters in javascript on an array of objects

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.

enter image description here

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'
}
]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!