Say I have the following object:
items = {
1: true,
2: false,
3: true,
4: true
},
How would I count the number of trues? So a simple function that would return the number 3 in this case.
You can reduce
the object's values
, coercing true
s to 1
and adding them to the accumulator:
const items = {
1: true,
2: false,
3: true,
4: true
};
console.log(
Object.values(items).reduce((a, item) => a + item, 0)
);
That's assuming the object only contains true
s and false
s, otherwise you'll have to explicitly test for true
:
const items = {
1: true,
2: false,
3: 'foobar',
4: true
};
console.log(
Object.values(items).reduce((a, item) => a + (item === true ? 1 : 0), 0)
);
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