I've been trying to figure out how to count the number of nested arrays recursively in javascript but I can't seem to wrap my head around how you would do that. Like I know we'll need to use a count variable in there and we'll need to be able to access the elements but how can we count each time a new array is seen inside? Here's the problem: Given a nested array where each element may be 1) an integer or 2) an array, whose elements themselves may be integers or further arrays, count the total number of arrays.
I've tried this and I have no clue what I'm doing when it comes to deciding whether we've seen a new array.
`
function countArrays(array) {
//counting the first array
let sumTotal = 1;
for(let element in array);
if(Array.isArray(array))
sumTotal = countArrays(array)
};
console.log(countArrays([1, 2, 3])) // 1
console.log(countArrays([1, [1, 2, 3], 3])) // 2
`
CodePudding user response:
You need to iterate the items, not keys of the array/object.
for (let element of array)
^^ ^
Omit semicolon, because this prevents the next statement to be a part of the loop. it is just the next statement after the loop.
Then check if the element is an array.
if (Array.isArray(element))
and the result of the recursive call with this item.
Finally return the count.
return sumTotal;
If no return stament is found, the function returns allways undefined
.
function countArrays(array) {
let sumTotal = 1;
for (let element of array)
if (Array.isArray(element))
sumTotal = countArrays(element);
return sumTotal;
}
console.log(countArrays([1, 2, 3])) // 1
console.log(countArrays([1, [1, 2, 3], 3])) // 2
Maybe it is easier to wrap all statments of lopps and conditions with a block statement to get a visual feedback of the scope of application.
function countArrays(array) {
let sumTotal = 1;
for (let element of array) {
if (Array.isArray(element)) {
sumTotal = countArrays(element);
}
}
return sumTotal;
}
console.log(countArrays([1, 2, 3])) // 1
console.log(countArrays([1, [1, 2, 3], 3])) // 2
CodePudding user response:
Another way you can do this is by just using a plain old for loop if you're confused on when to use a of or in loop. We can do this by getting the length of the array and looping through and looking for if that index in the array is indeed an array.
function countArray(arr) {
let count = 1;
for (let i = 0; i < arr.length; i ) {
if (Array.isArray(arr[i])) {
count ;
}
}
return count;
}