Eric Evans Eric Evans - 1 month ago 24
Javascript Question

Count Items recursively Javascript Array

I have an array that I want to recursively count items depending on what's item is pasted to function.

my array has a nested array how can I get a count of the items if the item that I'm searching for is apple

Here's my array

var arr = [
"apple",
["banana", "strawberry", "apple"]
];


And please don't down rate my question I've tried for the last few hours trying to figure this out and I'm lost and don't know where to start.

Here's one thing I tried

function countItems(arr, item) {
var count = 0;
for(var i = 0; i < arr.length;i++) {
if(arr[i] === item) {
count++;
}
}
return count;
}

Answer
function count(arr, itemName) {
  // Check if it's an array
  if (arr instanceof Array) {
    var ans = 0;
    // for each element call count recursively
    for (var i = 0; i < arr.length; ++i) {
      ans += count(arr[i], itemName);
    }
    // return result
    return ans;
  } else {
    // if it's not an array check if it is an required item then return 1/0         
    return itemName === arr;
  }
}
Comments