Search⌘ K

Count all Occurrences of a Number

Explore how to count every occurrence of a specific number within an array using recursion in JavaScript. Understand the step-by-step recursive process that breaks the problem into smaller tasks by checking elements and summing the results. This lesson builds foundational skills for solving array recursion problems and prepares you for interview challenges.

What does “Count all Occurrences of a Number” mean?

Our task is to find the number of times a key occurs in an array.

For example:

Number of occurrences of a key.
Number of occurrences of a key.

Implementation

Javascript (babel-node)
function count(myArray, key) {
// Base case
if (myArray.length == 0) {
return 0;
}
// Recursive case1
if (myArray[0] == key) {
return 1 + count(myArray.slice(1), key);
}
// Recursive case2
else {
return 0 + count(myArray.slice(1), key);
}
}
// Driver Code
myArray = [1, 2, 1, 4, 5, 1];
key = 1;
console.log(count(myArray, key));

Explanation

We need to count the number of times key occurs in an array. ...