Recursively loop through an array and return number of items with JavaScript?

We need to write a function that recursively searches through a nested array and counts how many times a specific value appears. This is useful when working with complex nested data structures.

Problem Statement

Given a nested array, we want to count all occurrences of a search term, including items in nested sub-arrays.

const names = ["rakesh", ["kalicharan", "krishna", "rakesh", "james", ["michael", "nathan", "rakesh", "george"]]];

For the above array, searching for "rakesh" should return 3 because it appears once at the top level and twice in nested arrays.

Recursive Solution

Here's a recursive function that traverses the entire nested structure:

const names = ["rakesh", ["kalicharan", "krishna", "rakesh", "james", 
["michael", "nathan", "rakesh", "george"]]];

const searchRecursively = (arr, query, count = 0, len = 0) => {
    if(len 

3
1
0

Simplified Recursive Approach

Here's a cleaner version using modern JavaScript syntax:

const countInNestedArray = (arr, query) => {
    let count = 0;
    
    for (let item of arr) {
        if (Array.isArray(item)) {
            count += countInNestedArray(item, query);
        } else if (item === query) {
            count++;
        }
    }
    
    return count;
};

const names = ["rakesh", ["kalicharan", "krishna", "rakesh", "james", 
["michael", "nathan", "rakesh", "george"]]];

console.log(countInNestedArray(names, "rakesh"));
console.log(countInNestedArray(names, "krishna"));
3
1

How It Works

The recursive function works by:

  • Base case: When we reach the end of an array, return the accumulated count
  • Recursive case 1: If current item is an array, recursively search within it
  • Recursive case 2: If current item matches the query, increment count and continue
  • Recursive case 3: If current item doesn't match, continue to next item

Comparison of Approaches

Method Readability Performance Memory Usage
Index-based recursion Complex Good Higher (extra parameters)
for...of recursion Better Good Lower

Conclusion

Recursive array traversal is perfect for nested structures of unknown depth. The simplified approach using for...of loops is more readable while maintaining the same functionality.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements