Use reduce to find number of times an items is in an array. The array could have arrays inside recursively.
var foo = [
1,
[2, 3, 4],
4, [5,6,7], 4
];
bar(foo, 4)
would return 3.
Try this one using Array.prototype.reduce
.
var foo = [1, [2, 3, 4], 4, [5, 6, 7], 4];
function f(arr, item) {
return arr.reduce(function (s, i) {
if (Array.isArray(i)) return s+f(i, item);
return s+(i==item?1:0);
}, 0);
}
console.log(f(foo, 4))
The function f
is a recursive function. We loop over all the items and reduce them to one number. The function would be called on all the inner arrays as well, and for the non-array items, we just check them to be equal to the desired item.
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