title: Sort flat array by parentId javascript
body: <p>Every parent element should contain total count of all subcategories. It will be very good if solution will be using <strong>only Array object methods and no using of <code>while</code> loops.</strong> </p>
  
  <p>This is the example of base structure:</p>
  
  <pre><code>const base = [
    { id: 1, count: 2, parentId: null },
    { id: 2, count: 4, parentId: 1 },
    { id: 3, count: 0, parentId: 2 },
    { id: 6, count: 8, parentId: 3 },
    { id: 7, count: 8, parentId: 3 },
    { id: 8, count: 2, parentId: 7 },
    { id: 4, count: 2, parentId: null },
    { id: 5, count: 1, parentId: 4 },
  ];
  </code></pre>
  
  <p>This is how it should be looking like:</p>
  
  <pre><code>const expected = [
    { id: 1, count: 2, total: 24, parentId: null },
    { id: 2, count: 4, total: 22, parentId: 1 },
    { id: 3, count: 0, total: 18, parentId: 2 },
    { id: 6, count: 8, total: 8, parentId: 3 },
    { id: 7, count: 8, total: 10, parentId: 3 },
    { id: 8, count: 2, total: 2, parentId: 7 },
    { id: 4, count: 2, total: 3, parentId: null },
    { id: 5, count: 1, total: 1, parentId: 4 },
  ];
  </code></pre>
  
  <p>Here's my current code. I think here somehow I need go to the last level 
  and then starting from last item to top concataning prev level with current
  level <code>count</code> prop value that is why I made named IIFE.</p>
  
  <pre><code>let c = a.map(cat =&gt; {
    const top = a.filter(v =&gt; cat.id === v.parentId);
    let test;
    return ({
      ...cat,
      total: (test = categs =&gt; {
        return categs.reduce((acc, val) =&gt; {
           /* ??? */
           return acc + val.count
        }, cat.count);
      })(top)
    })
  })
  </code></pre>