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

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 −


Updated on: 24-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started