Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Counting elements of an array using a recursive function in JS?
A recursive function calls itself until a base condition is met. In JavaScript, we can use recursion to count array elements by reducing the array size in each recursive call.
How Recursive Counting Works
The recursive approach works by:
- Base case: If array is empty, return 0
- Recursive case: Return 1 + count of remaining elements
Example
function countNumberOfElementsUsingRecursive(listOfMarks) {
if (listOfMarks.length == 0) {
return 0;
}
return 1 + countNumberOfElementsUsingRecursive(listOfMarks.slice(1));
}
var listOfMarks = [56, 78, 90, 94, 91, 82, 77];
console.log("The array:");
console.log(listOfMarks);
var numberOfElements = countNumberOfElementsUsingRecursive(listOfMarks);
console.log("The Number of elements = " + numberOfElements);
The array: [ 56, 78, 90, 94, 91, 82, 77 ] The Number of elements = 7
Step-by-Step Execution
Here's how the recursion works for array [1, 2, 3]:
function countElements(arr) {
console.log("Current array:", arr);
if (arr.length == 0) {
console.log("Base case reached, returning 0");
return 0;
}
console.log("Returning 1 + count of remaining elements");
return 1 + countElements(arr.slice(1));
}
var testArray = [1, 2, 3];
var result = countElements(testArray);
console.log("Final count:", result);
Current array: [ 1, 2, 3 ] Returning 1 + count of remaining elements Current array: [ 2, 3 ] Returning 1 + count of remaining elements Current array: [ 3 ] Returning 1 + count of remaining elements Current array: [] Base case reached, returning 0 Final count: 3
Alternative Recursive Approach
Using array index instead of slice() for better performance:
function countWithIndex(arr, index = 0) {
if (index >= arr.length) {
return 0;
}
return 1 + countWithIndex(arr, index + 1);
}
var numbers = [10, 20, 30, 40, 50];
console.log("Array:", numbers);
console.log("Count using index approach:", countWithIndex(numbers));
Array: [ 10, 20, 30, 40, 50 ] Count using index approach: 5
Comparison
| Method | Performance | Memory Usage |
|---|---|---|
| slice() approach | Slower (creates new arrays) | Higher |
| Index approach | Faster | Lower |
| Built-in length | Fastest | Lowest |
Conclusion
Recursive counting demonstrates how recursion works with arrays. While educational, use the built-in array.length property for actual counting needs as it's more efficient.
Advertisements
