devdropper87 devdropper87 - 1 month ago 11
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

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);
}