1

Hi guys I am trying to solve this problem but can't figure out how to compare a typeof array which is object with a type of object... basically How to exclude from my final count everything that is not "real" Object, this is the problem:

This function takes an array of different data types. It should return a count of the number of objects in the array.

my code should explain a little bit better my meaning:

function countTheObjects(arr) {
  let howManyObj = 0;
  arr.forEach(function (type) {
    console.log(typeof type);
    if (typeof type === "object" && type !== null) {
      howManyObj++;
    }
  });

  return howManyObj;
  
}

console.log(
  countTheObjects([1, {}, [], null, null, "foo", 3, 4, 5, {}, {}, {}, "foo"])
);

the final count is 5 but it should be 4. I tried to add in the condition the

(typeof type === "object" && type !== null && type !== [])

but without result. I am trying to understand how to exclude from the count the []..

if I console.log(typeof []) the result is object. so I think I am approaching this problem in a wrong way.

thank you for your support.

1 Answer 1

2

You could use Array.isArray() to check.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

 if (typeof type === "object" && type !== null && !Array.isArray(type)) {
      howManyObj++;
    }
Sign up to request clarification or add additional context in comments.

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.