Count A Given Item from Multi Dimensional Arrays in Javascript

This can be achieved by using recursion in javascript.

function countItems(arr, item) {
  // Write the code that goes here
  var count  = 0;
  for(var i = 0; i < arr.length; ++i)
  {
    if(Array.isArray(arr[i]))
      {
        count +=countItems(arr[i], item);
      }
    else
      {
        if(arr[i] == item)
        count++;
     }
   }
  
  return count;
}

var arr = [
  "apple",
  ["banana", "strawberry", "apple"],
  "apple",
  ["banana", "strawberry",
  ["banana", "strawberry", "apple"],
  "apple"]
];
console.log(countItems(arr, "apple")); //output

Leave a Reply

Your email address will not be published. Required fields are marked *