Given a multidimensional array like this:
var arr = [
\"apple\",
[\"banana\", \"strawberry\",\"dsffsd\", \"apple\"],
\"banana\",
[\"sdfdsf\",\"apple\",[\"apple\
I think this is a simple approach but you can get tangled with it:
function countItems(arr, item, count = 0){
if(!arr.length) return count; //if the array is empty then there's nothing else to count
let cTemp;
if(Array.isArray(arr[0])){ //if the next item is an array
cTemp = countItems(arr[0], item); //count the items in that array
} else {
cTemp = arr[0] === item ? 1 : 0; //if it's a string the compare it with item
//1 if we found it
//0 if we didn't
}
return countItems(arr.slice(1), item, count+cTemp);
//count the items of the rest of the array and add what we found
//arr.slice(1) is the rest of the array
//cTemp is the count for the first item in the array
}
Which of course can be rewritten into a single line:
let countItems = ([first, ...rest], item, count = 0) => !first ? count : countItems(rest, item, count + (Array.isArray(first) ? countItems(first, item) : +(first === item)))