Count array except the empty values

I have an array of objects like this:

 var a = [{'id': 1}, {'id':''}, {'id':3}]

And now I need to count the array except the empty id so the answer should be 2.
I tried to used filter function but I couldn’t get my expected out put.

This is the codes I am done so far.

         a.filter(Boolean).length; // Returns 3. It should be 2.

Any idea is much appreciated. Thank you

2 thoughts on “Count array except the empty values”

  1. Try using reduce.

    const array = [{'id': 1}, {'id':''}, {'id':3}]
    
    const count = array.reduce((acc, cur) => {
     if (cur.id !== '') {
       acc += 1
     }
     return acc
    }, 0)
    
    console.log(count)

    array.filter(Boolean).length is returns 3 because filter returns elements if provider returns true, In your case, passing object to Boolean({…}) which returns true, so it keeps all the elements.

    Reply
  2. // Your array
    const arr = [{'id': 1}, {'id':''}, {'id':3}]
    
    // Filter returns a new array with elements that match the condition below
    const length = arr.filter( element => element.id != "" ).length;
    
    console.log(length)
    Reply

Leave a Comment