N
N
Neuro2020-04-14 15:48:24
JavaScript
Neuro, 2020-04-14 15:48:24

How to sum all values ​​in a tree?

Good afternoon, there is such an array with a tree object inside:

[
  {
    "id": 1,
    "parentid": null,
    "count": "0",
    "children": [
      {
        "id": 2,
        "parentid": 1,
        "count": "89",
        "children": [
          {
            "id": 3,
            "parentid": 2,
            "count": "19",
            "children": [
              {
                "id": 5,
                "parentid": 3,
                "count": "205"
              },
              {
                "id": 4,
                "parentid": 3,
                "count": "8"
              }
            ]
          }
        ]
      }
    ]
  }
]


I need to sum all count values ​​from children and add them to the parent, does anyone know the solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-04-14
@Riveran

const addSum = data =>
  (Array.isArray(data) ? data : []).reduce((acc, n) => {
    n.childrenCountSum = addSum(n.children);
    return acc + +n.count + n.childrenCountSum;
  }, 0);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question