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
>Solution :
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));