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

JavascriptWeb DevelopmentObject Oriented Programming

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
raja
Published on 25-Aug-2020 07:05:04
Advertisements