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.
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.
Share Improve this question edited Mar 13, 2021 at 12:59 halfer 20.4k19 gold badges108 silver badges201 bronze badges asked Oct 17, 2018 at 3:17 cup_ofcup_of 6,69710 gold badges51 silver badges104 bronze badges 04 Answers
Reset to default 11You 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)
);
const items = {
a: false,
b: true,
c: false,
d: false,
e: false
};
const count = Object.values(items).filter(item => item === true).length;
console.log(count);//1
var items = {
1: true,
2: false,
3: true,
4: true
};
function countTrue4obj(obj) {
var count = 0;
for (var p in obj) {
if (obj.hasOwnProperty(p) && obj[p] === true) {
count++
}
}
return count;
}
console.log(countTrue4obj(items));
You might consider using a Set
. Rather than storing true
and false
, simply add
or delete
.
const items = new Set();
items.add(1)
items.add(3)
items.add(4)
// 3
console.log(items.size)