skip to Main Content

please I need help with this

const obj = {a="", b="good", c=false, d="", e="excellent"}

I just want to know total empty and false. where my answer is suppose to be 3.

const obj = {a="", b="good", c=false, d="", e="excellent"}

for (let k in obj) {
  if (obj[k] === '' || obj[k] === false) {
    //console.log(k);

  }
}

Any pointers will be greatly appreciated

THank you

4

Answers


  1. You could just make an array and put the keys that are empty into it. That way, at the end of the program, the length of the array will be the number of empty elements.

    const obj = {a:"", b:"good", c:false, d:"", e:"excellent"}
    const emptyElements = [] // an array containing all the keys of the properties that are empty
    for (let key in obj) {
      if (obj[key] === '' || obj[key] === false) {
        // Key is empty
        emptyElements.push(k)
      }
    }
    console.log(emptyElements.length) // the number of empty elements in the object
    

    Or you could simply add a variable that increments whenever it finds an empty value.

    const obj = {a:"", b:"good", c:false, d:"", e:"excellent"}
    let nEmptyElements = 0 // Number of empty elements
    for (let key in obj) {
      if (obj[key] === '' || obj[key] === false) {
        // Key is empty
        nEmptyElements += 1 // Increment the number of empty element
      }
    }
    console.log(nEmptyElements) // the number of empty elements in the object
    

    Hope this helps

    Login or Signup to reply.
  2. const obj = {a:"", b:"good", c:false, d:"", e:"excellent"};
    
    let count = 0; 
    
    for (let k in obj) {
      if (obj[k] === '' || obj[k] === false) {
        count++; 
      }
    }
    
    console.log(count); 
    Login or Signup to reply.
  3. You can reduce over Object.values.

    const obj = {a: "", b: "good", c: false, d: "", e: "excellent"};
    let falsyValuesCount = Object.values(obj).reduce((a, c) => a + !c, 0);
    console.log(falsyValuesCount);

    To get the actual values that were falsy, use Array#filter instead.

    Login or Signup to reply.
  4. Here’s a one liner to archieve your result set using Array.Prototype.filter :

    const obj = {a: "", b: "good", c: false, d: "", e: "excellent"};
    
    const resultArray = Object.values(obj).filter(value => value === '' || value === false);
    
    console.log("Count :", resultArray.length); 
    console.log("Array values :", JSON.stringify(resultArray));

    Read more on Array.Prototype.filter operation here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search