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

186
Views
How to get length of multidimensionnel array

I want to get length of multidimentionnal array in JS : This is my array :

const treeData = [
  {
    title: '0-0',
    key: '0-0',
    children: [
      {
        title: '0-0-0',
        key: '0-0-0',
        children: [
          {
            title: '0-0-0-0',
            key: '0-0-0-0',
          },
          {
            title: '0-0-0-1',
            key: '0-0-0-1',
          },
          {
            title: '0-0-0-2',
            key: '0-0-0-2',
          },
        ],
      },
      {
        title: '0-0-1',
        key: '0-0-1',
        children: [
          {
            title: '0-0-1-0',
            key: '0-0-1-0',
          },
          {
            title: '0-0-1-1',
            key: '0-0-1-1',
          },
          {
            title: '0-0-1-2',
            key: '0-0-1-2',
          },
        ],
      },
      {
        title: '0-0-2',
        key: '0-0-2',
      },
    ],
  },
  {
    title: '0-1',
    key: '0-1',
    children: [
      {
        title: '0-1-0-0',
        key: '0-1-0-0',
      },
      {
        title: '0-1-0-1',
        key: '0-1-0-1',
      },
      {
        title: '0-1-0-2',
        key: '0-1-0-2',
      },
    ],
  },
  {
    title: '0-2',
    key: '0-2',
  },
];

The output should be : 15 The idea is to map trough all elements and if they have an array child, get the lentgh of it I'm sure that I will go for a récursive function but it seems to be tricky.. I did'nt found any solutions in internet, have you an idea please ? Thank you

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

0

function getLengthOfTreeData(treeData) {
    let size = { size: 0 }; // object because it needs to be passed by reference
    return getSize(size, treeData).size;
}

function getSize(size, treeData) { // recursive function
    if (treeData.length === 0) {
        return size;
    }

    size.size += treeData.length;
    for (let i = 0; i < treeData.length; i++) {
        const data = treeData[i];
        if (data.children) getSize(size, data.children);
    }
    return size;
}

console.log(getLengthOfTreeData(treeData));
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!