0

Say I have an array, like so:

arr = [{}, {}, {}, {}]

I want to be able to know the length of the array, only counting objects within in it that have at least one property.

[{}, {name: "Derby County", odds: 2}, {}, {}] // 1

[{}, {name: "Derby County", odds: 2}, {name: "Fullham", odds: 3} ,{}] // 2

How do I achieve this?

4
  • Object.keys(obj).length will yield a non-zero result when there's at least one iterable, non-inherited property. Commented Mar 9, 2019 at 2:27
  • detect when something is added this has more than one way to interpret it, with quite different solutions Commented Mar 9, 2019 at 2:41
  • You're right @AndréWerlang I'll update OP now, thank you Commented Mar 9, 2019 at 2:52
  • I've updated the OP, hopefully that's clearer? Commented Mar 9, 2019 at 2:56

2 Answers 2

1
arr.filter(x => Object.keys(x).length).length

As explained in other answers, Object.keys() returns property names from a given object. The inner .length is a shortcut to filter only items that have at least one property. The outer .length tells how many objects fit the description.

UPDATE:

The [].filter() method takes a function that returns a thruthy/falsy value. A number greater than 0 is thruthy, so it's the same as .length !== 0.

The assumption here is that any element contained in the array is non-null. Under this assumption it makes no sense checking the object for null inside the [].filter(). When using TypeScript, it's a static check for arr. If the assumption is broken, then an error is thrown, which it's something I usually desire. I don't hide runtime errors. If there's a runtime error here, I'll review the assumption. Yet I'm not sure it's the case here.

Sign up to request clarification or add additional context in comments.

4 Comments

Remember to check for null arr.filter(x => x ? Object.keys(x).length > 0 : false).length;
Thanks for the reply and sorry, I've updated the OP again! Hopefully now I've articulated myself properly
@A7DC the edit doesn't change the answer, it still complies, I guess the .length access made you think it would accumulate properties?
@ThilinaHasantha it's a valid assumption to expect the input array contains only non-null objects. Besides, it can be also desired it throws an error if that assumption fails
1

If you do:

arr.map(x=> Object.keys(x).length)

you'll get:

[ 0, 0, 0, 1 ]

If the object is empty then there are no keys and so its length is 0.

If you need a true/false result do:

arr.map(x=> Object.keys(x).length).some(x=>x>0)

Examples:

console.log("[{},{}]", [{},{}].map(x=> Object.keys(x).length).some(x=>x>0))

console.log("[{},{a: 1}]", [{},{a: 1}].map(x=> Object.keys(x).length).some(x=>x>0))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.