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

JavascriptWeb DevelopmentObject Oriented Programming

We have to write a function, say searchRecursively() that takes in an array and a search query and returns the count of that search query in the nested array.

For example, if the array is given by −

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

Then −

searchRecursively(names, ‘’rakesh’);

Should return 3 because it makes a total of 3 appearances in the array. Therefore, let’s write the code for this recursive function −


const names = ["rakesh", ["kalicharan", "krishna", "rakesh", "james",
["michael", "nathan", "rakesh", "george"]]];
const searchRecursively = (arr, query, count = 0, len = 0) => {
   if(len < arr.length){
         return searchRecursively(arr[len], query, count, 0);
      if(arr[len] === query){
         return searchRecursively(arr, query, ++count, ++len);
      return searchRecursively(arr, query, count, ++len);
   return count;
console.log(searchRecursively(names, "rakesh"));


The output in the console will be −

Published on 24-Aug-2020 05:40:47