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

108
Views
How to get totalCount of elements where id matches parentId

I have following structure:

const arr = [
  { id: 1, count: 0, parentId: null },
  { id: 2, count: 30, parentId: 1 },
  { id: 3, count: 1, parentId: 2 }
];

and I want to get this result

const res = [
  { id: 1, totalCount: 30 },
  { id: 2, totalCount: 31 },
  { id: 3, totalCount: 1 },
]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Yu need to iterate over the array, filter out the items that have the matching the parent id and sum the counts using reduce() and add that to the existing count on each item.

const arr = [
  { id: 1, count: 0, parentId: null },
  { id: 2, count: 30, parentId: 1 },
  { id: 3, count: 1, parentId: 2 }
];

const result= [];
arr.forEach((item)=> {
  const  id = item.id;
  const items = arr.filter(x => x.parentId === item.id);
  const totalCount = item.count +  items.reduce((partialSum, a) => partialSum + a.count, 0);
  result.push({id,totalCount})
})

 console.log(result); // gives the following
 /*[
  {id: 1, totalCount:30}, 
  {id: 2, totalCount:31},
  {id: 3, totalCount: 1} 
]*/

about 4 years ago · Juan Pablo Isaza Report

0

this code will give you the desired result:

const arr = [
    { id: 1, count: 0, parentId: null },
    { id: 2, count: 30, parentId: 1 },
    { id: 3, count: 1, parentId: 2 }
];
const newArr = arr.map((element) => {
    const parent = arr.find((item) => {
        return item.parentId === element.id
    });
    const totalCount = parent ? element.count + parent.count : element.count;
    return {id: element.id, totalCount};
});
console.log(newArr);
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!