Counting how many times an item appears in a multidimensional array in JavaScript

We have a nested array of strings and we have to write a function that accepts the array and a search string and returns the count of the number of times that string appears in the nested array.

Therefore, let's write the code for this, we will use recursion here to search inside of the nested array and the code for this will be ?

Example

const arr = [
   "apple",
   ["banana", "strawberry","dsffsd", "apple"],
   "banana",
   ["sdfdsf","apple",["apple",["nonapple", "apple",["apple"]]]]
   ,"apple"];

const calculateCount = (arr, query) => {
    let count = 0;
    for(let i = 0; i 

Output

The output in the console will be ?

7

How It Works

The function uses recursion to traverse the multidimensional array:

  1. For each element, check if it matches the search query
  2. If it's a match, increment the counter
  3. If the element is itself an array, recursively call the function on that sub-array
  4. Add the results from nested arrays to the main counter

Alternative Using Array.flat()

For simpler cases, you can flatten the array first:

const countWithFlat = (arr, query) => {
    return arr.flat(Infinity).filter(item => item === query).length;
};

console.log(countWithFlat(arr, "apple"));
7

Comparison

Method Memory Usage Performance Readability
Recursive Lower Better for large arrays More complex
Array.flat() Higher Creates new array More readable

Conclusion

The recursive approach efficiently counts occurrences in multidimensional arrays without creating additional arrays. Use Array.flat() for simpler cases where memory isn't a concern.

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements