Given a multidimensional array like this:
var arr = [
\"apple\",
[\"banana\", \"strawberry\",\"dsffsd\", \"apple\"],
\"banana\",
[\"sdfdsf\",\"apple\",[\"apple\
You could take a recursive approach for arrays or check the value and add the result of the boolean value.
function count(array, value) {
return array.reduce((s, a) => s + (Array.isArray(a) ? count(a, value) : a === value), 0);
}
var array = ["apple", ["banana", "strawberry", "dsffsd", "apple"], "banana", ["sdfdsf", "apple", ["apple", ["nonapple", "apple", ["apple"]]]], "apple"];
console.log(count(array, 'apple'));
Version with a for
loop.
function count(array, value) {
var i,
sum = 0;
for (i = 0; i < array.length; i++) {
if (Array.isArray(array[i])) {
sum += count(array[i], value);
continue;
}
sum += array[i] === value;
}
return sum;
}
var array = ["apple", ["banana", "strawberry", "dsffsd", "apple"], "banana", ["sdfdsf", "apple", ["apple", ["nonapple", "apple", ["apple"]]]], "apple"];
console.log(count(array, 'apple'));