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 < arr.length; i++){
         if(arr[i] === query){
            count++;
            continue;
      };
      if(Array.isArray(arr[i])){
         count += calculateCount(arr[i], query);
      }
   };
   return count;
};
console.log(calculateCount(arr, "apple"));

Output

The output in the console will be −

7

Updated on: 25-Aug-2020

700 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements