Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of trues in a JavaScript object

Tags:

javascript

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.

like image 242
cup_of Avatar asked Sep 12 '25 18:09

cup_of


1 Answers

You can reduce the object's values, coercing trues 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 trues and falses, 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)
);
like image 79
CertainPerformance Avatar answered Sep 15 '25 07:09

CertainPerformance