devdropper87 - 1 year ago 83
Javascript Question

Counting number of occurrences recursively

Why is this recursive countOccurence function not working? this has a subroutine. is there a way to do it without a subroutine? it seems in javascript you have to have a closure (subroutine function) for the counter variable, otherwise it gets rewritten every time!

``````function numOccurencesRecursive(arr, val) {
//base case. check it if it only has a length of 1
var count = 0;

function doCount(arr, val) {
if (arr[0] === val) {
count++;
} else {
count += doCount(arr.slice(1), val)
}
return count;
}

return doCount(arr, val);
}

console.log(numOccurencesRecursive([2, 7, 4, 4, 1, 4], 4)); // should return 3 but returns 1
``````

Answer Source

I think the problem is that you were thinking iteratively but used a recursive approach.

The iterative approach has a global variable which may be updated at each step:

``````function numOccurencesIterative(arr, val) {
var count = 0;
for(var i=0; i<arr.length; ++i) if(arr[i] === val) ++count;
return count;
}
``````

However, when using recursive approaches, better avoid global variables.

``````function numOccurencesRecursive(arr, val) {
if(!arr.length) return 0;
return (arr[0] === val) + numOccurencesRecursive(arr.slice(1), val);
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download