Count all Occurrences of a Number
In this lesson, we will learn how to count all occurrences of a key in a given array.
We'll cover the following...
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.
Implementation
Press + to interact
function count(myArray, key) {// Base caseif (myArray.length == 0) {return 0;}// Recursive case1if (myArray[0] == key) {return 1 + count(myArray.slice(1), key);}// Recursive case2else {return 0 + count(myArray.slice(1), key);}}// Driver CodemyArray = [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. ...