0

Let my object have the following data:

{
  mongoose: {
    name: "Starky",
    age: 3,
    playful: false
  },
  dog: {
    name: "Maks",
    age: 7,
    playful: false
  },
  parrot: {
    name: "Petty",
    age: 4,
    playful: true
  }
}

How can I count the number of booleans?
I know that I can use .reduce, but I didn’t understand exactly how to use it correctly, in an attempt to use it, I just got undefined.

  • Does this answer your questions? (may need to rework for your object) - https://stackoverflow.com/questions/42317140/count-the-number-of-true-members-in-an-array-of-boolean-values – Jake Jun 08 '22 at 11:50
  • @Jake I remember here I was looking for something that could help, but for some reason it did not help. –  Jun 08 '22 at 12:29

3 Answers3

2

Here,

var d = {
  mongoose: {
    name: "Starky",
    age: 3,
    playful: false
  },
  dog: {
    name: "Maks",
    age: 7,
    playful: false
  },
  parrot: {
    name: "Petty",
    age: 4,
    playful: true
  }
}
console.log('Data',d) //Console for data

function cc(){ //Create function
    let totalBool=0;
    let totalTrue=0;
    let totalFalse=0;
Object.keys(d).forEach((x)=>{
    let dd = Object.keys(d[x]);
    dd.forEach((y)=>{
        if(typeof(d[x][y])=='boolean')
            {totalBool++}
        if(d[x][y]==true)
            {totalTrue++}
        if(d[x][y]==false)
            {totalFalse++}
    })})
    console.log('TotalBool :',totalBool);
    console.log('TotalTrue :',totalTrue);
    console.log('TotalFalse :',totalFalse);}
console.log(cc()) // Console for know bool value
0

you can do something like this

to check if it is a boolean I have used !! and ===

const countBoolean = data => Object
.entries(data)
.reduce((res, [k, v]) => {
  return res + Object.values(v).filter(value => value === !!value).length
}, 0)

const data = {
  mongoose: {
    name: "Starky",
    age: 3,
    playful: false
  },
  dog: {
    name: "Maks",
    age: 7,
    playful: false
  },
  parrot: {
    name: "Petty",
    age: 4,
    playful: true
  }
}

console.log(countBoolean(data))
R4ncid
  • 6,944
  • 1
  • 4
  • 18
0

You can use Array.prototype.reduce twice to count all the boolean values.

const 
  data = {
    mongoose: { name: "Starky", age: 3, playful: false },
    dog: { name: "Maks", age: 7, playful: false },
    parrot: { name: "Petty", age: 4, playful: true },
  },
  numBools = Object.values(data).reduce(
    (total, o) =>
      total + Object.values(o).reduce((t, v) => (typeof v === "boolean" ? t + 1 : t), 0),
    0
  );

console.log(numBools);
SSM
  • 2,855
  • 1
  • 3
  • 10