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:

  1. Starting with the current array's length as the initial accumulator
  2. For each element, checking if it's an array using Array.isArray()
  3. If it's an array, recursively calling deepCount() on that nested array
  4. Adding the nested count to the accumulator
  5. 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.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements