Recursively loop through an array and return number of items?

Viewed 12248

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");

6 Answers

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

function loop(arr, item) {
    let res = 0;

    for (let v of arr) {
        if (typeof v === 'object') res += loop(v, item);
        if (v === item) res++;
    }

    return res;    
}



const result = loop(names, "bob");
console.log(result);

As of 2020, we have Array.prototype.flat method which makes this task trivial.

Here you go.

const names = ["bob", ["steve", "michael", "bob", "chris"]];
const nestedNames = ["bob", ["steve", ["michael", ["bob", ["chris"]]]]];

function countName(array, name, depth = Infinity) {
  return array.flat(depth).reduce((acc, cur) => acc + (cur === name ? 1 : 0), 0);
}

console.log(countName(names, 'bob')); // 2
console.log(countName(names, 'chris')); // 1

console.log(countName(nestedNames, 'bob')); // 2
console.log(countName(nestedNames, 'chris')); // 1

Related