Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively loop through an array and return number of items?

I apologize if this has been asked before but I could not find an answer. How do I loop through an array with nested arrays and in the console print out the number of instances an item appears?

So console.log should print out the number 2 for the name "bob" because "bob" appears twice in the array.

Here is my array and what I have so far:

    var names = ["bob", ["steve", "michael", "bob", "chris"]];

    function loop(arr, item) {
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] instanceof Array) {
          loop(arr[i], item);
        } else {
          if (arr[i] == item) {
            console.log(arr[i]);
          }
        }
      }
    }

    loop(names, "bob");
like image 597
stalwil Avatar asked Dec 11 '22 18:12

stalwil


1 Answers

here you go, note that you can keep the counter value internally, to keep the rest of your code cleaner:

var names = ["bob", ["steve", "michael", "bob", "chris"]];

function loop(arr, item) {
  var result = 0;
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] instanceof Array) {
      result += loop(arr[i], item);
    } else {
      if (arr[i] == item) {
        result++;
      }
    }
  }
  return result;    
}


var result = loop(names, "bob");
console.log(result);
like image 61
jberndsen Avatar answered Jan 12 '23 01:01

jberndsen