arr.filter(x => Object.keys(x).length).length
Another way to understand the code above is that the Object.keys()
function returns the names of properties from a given object. The first .length
filters only items with at least one property, while the second .length
counts how many objects meet this criteria.
UPDATE:
In the [].filter()
method, it takes a function that results in a true or false value. Any number greater than 0 is considered as true, which is equivalent to .length !== 0
.
The assumption made here is that every element in the array is non-null. With this assumption, checking for null values inside the [].filter()
doesn't make sense. In TypeScript, this provides a static check for the variable arr
. If this assumption is incorrect and there are null values present, an error will be thrown, something that I prefer as it helps uncover issues. Runtime errors are not hidden in my code, and if there are any, I will reassess the underlying assumption. However, I don't think that's the case here.