0

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

Dan
  • 59,490
  • 13
  • 101
  • 110
  • can you explain what `a.filter(Boolean).length;` is trying to do? – D. Seah Feb 19 '21 at 04:41
  • I think you have misunderstood the documentation. You don't place the literal word "Boolean" as the argument for `filter`. You pass something that returns true or false depending on whether you keep or exclude each item in the array. By passing `Boolean`, you're simply returning a non-false value for every element, so it doesn't work. Try this example out to understand filter better: https://codepen.io/garethredfern/pen/zBLLYW – Chris Baker Feb 19 '21 at 06:27

3 Answers3

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

Naren
  • 4,152
  • 3
  • 17
  • 28
1
const length = Object.fromEntries(Object.entries(arr).filter(([_, v]) => v.id != '')).length;

console.log(length);

You can also use Object.fromEntries to bypass object element that does not match

shalini
  • 1,291
  • 11
  • 13