user19294310
user19294310

Reputation:

Count the number of booleans (JavaScript)

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.

Upvotes: 0

Views: 157

Answers (3)

Som Shekhar Mukherjee
Som Shekhar Mukherjee

Reputation: 8188

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);

Upvotes: 0

Ravindra Nakrani
Ravindra Nakrani

Reputation: 129

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

Upvotes: 2

R4ncid
R4ncid

Reputation: 7139

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))

Upvotes: 0

Related Questions