Sure! Here is a JavaScript function numberOfItems that does what you described:
function numberOfItems(arr, item) {
var count = 0;
if (Array.isArray(arr)) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) {
count++;
}
count += numberOfItems(arr[i], item);
}
} else {
for (var key in arr) {
if (arr[key] === item) {
count++;
}
count += numberOfItems(arr[key], item);
}
}
return count;
}
Here's an explanation of how the function works:
- It takes two parameters:
arr (the array to search) and item (the item to search for).
- It first checks if
arr is an array using Array.isArray(). If it is, it iterates over the array using a for loop.
- Inside the loop, it checks if the current item in the array is equal to
item using the === operator. If it is, it increments a count variable count using count++.
- If the current item is also an array, it recursively calls
numberOfItems on it, passing in item as the second argument. This allows the function to search nested arrays as well.
- After iterating over the entire array, it returns
count, which is the number of occurrences of item in arr.
- If
arr is not an array, it iterates over the keys and values of the object using a for...in loop. It checks if the value for each key is equal to item, and if so, it increments count as before.
- Finally, it returns
count.
Here's an example usage of the function:
console.log(numberOfItems([1, 2, 3, [4, [5, 6], 7], 8], 4)); // output: 2
In this example, the function is called with an array `arr