Given a multidimensional array like this:
var arr = [
\"apple\",
[\"banana\", \"strawberry\",\"dsffsd\", \"apple\"],
\"banana\",
[\"sdfdsf\",\"apple\",[\"apple\
i think if you continue to return the count value and use it in your calculation you will be able to to get a final number without an outside variable:
function countItems(arr, item) {
let totc = 0; // totc is now local
for (let i = 0; i < arr.length; i++ ){ // iterate on arr
let isarray = arr[i].constructor === Array; // if the element is a nested array
if(isarray){ totc += countItems(arr[i], item) } // recursion, using the return value
let isin = arr[i] === item; // ELSE if the item is in the arr
if(isin) { totc ++; };
}
return totc; // the length of the sum array show how many items founded
}
}
note that the only changes i made were to instantiate totc inside the function and to take the result of recursive calls and add them to the local total.
Nina's answer is more elegant, but perhaps this will be easier to understand.