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");
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With