Home > Software design >  How to compare typeof array[] with typeof object{}
How to compare typeof array[] with typeof object{}

Time:10-20

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.

CodePudding user response:

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  ;
    }
  • Related