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
Deep count of elements of an array using JavaScript
We are required to write a JavaScript function that takes in a nested array of elements and returns the deep count of all elements present in the array, including those in nested subarrays.
Problem
Given a nested array, we need to count all elements at every level of nesting.
Input
const arr = [1, 2, [3, 4, [5]]];
Output
const output = 7;
Because the elements at level 1 are 2, elements at level 2 are 2 and elements at level 3 are 1. Hence the deep count is 7.
Using Recursive Reduce Method
The most elegant approach uses Array.reduce() with recursion to traverse nested arrays:
const arr = [1, 2, [3, 4, [5]]];
const deepCount = (arr = []) => {
return arr.reduce((acc, val) => {
return acc + (Array.isArray(val) ? deepCount(val) : 0);
}, arr.length);
};
console.log(deepCount(arr));
console.log(deepCount([1, [2, [3, [4]]]]));
console.log(deepCount([]));
7 4 0
How It Works
The function works by:
- Starting with the current array's length as the initial accumulator
- For each element, checking if it's an array using
Array.isArray() - If it's an array, recursively calling
deepCount()on that nested array - Adding the nested count to the accumulator
- Non-array elements don't add to the count (they're already counted in the initial length)
Alternative Approach Using Stack
Here's an iterative solution using a stack to avoid recursion:
const deepCountIterative = (arr) => {
let count = 0;
const stack = [...arr];
while (stack.length > 0) {
const current = stack.pop();
count++;
if (Array.isArray(current)) {
stack.push(...current);
}
}
return count;
};
const arr = [1, 2, [3, 4, [5]]];
console.log(deepCountIterative(arr));
7
Comparison
| Method | Approach | Memory Usage | Readability |
|---|---|---|---|
| Recursive Reduce | Functional | Call stack | High |
| Iterative Stack | Imperative | Manual stack | Medium |
Conclusion
The recursive reduce() approach provides a clean, functional solution for counting all elements in nested arrays. It elegantly handles arrays of any nesting depth by recursively processing subarrays.
