Suppose I have an array containing the following objects:
arr = [{name: 'foo', number: 1}, {name: 'foo', number: 1}, {name: 'bar', number: 1}]
How can I determine the count of foo
in this array without explicitly passing the name?
search(name, arr) {
let fooCount = 0;
let barCount = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i].name === 'foo') {
fooCount++;
} else if (arr[i].name === 'bar') {
barCount++;
}
}
return { foo: fooCount, bar: barCount };
}
This enables me to call the search()
function and obtain counts for both foo
and bar
from the array.