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

196
Views
i have a case, how to sum all commentId in this variable? Has anyone had the same case?

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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