0

just looking for a little help. I think I've overcomplicated this. Basically I'm trying to just count the objects in this array filled with different data types. I tried just to separate the objects and count them, but obviously I'm now getting both arrays and objects and counting them. The below outputs 4 when it should be 3.

Any help appreciated, still new to coding.

function countTheObjects(arr) {

let objects = [];
for (let i = 0; i < arr.length; i++) {
  if (typeof arr[i] === 'object')
    objects.push(arr[i]);
}
  return objects.length;
}

console.log((countTheObjects([1, [], 3, 4, 5, {}, {}, {}, 'foo'])))
2
  • 2
    You can identify whether an object is also an array with Array.isArray. But what will you do with sets, maps, regexes, dates, ...etc, will they count as objects or not? Commented Aug 29, 2022 at 13:12
  • Arrays are Objects which is why you’re getting the answer you are. As others have mentioned, use Array.isArray() to test for “array-ness”. Commented Aug 29, 2022 at 13:18

3 Answers 3

1
function countTheObjects(arr) {
let objects = [];
for (let i = 0; i < arr.length; i++) {
  if (!Array.isArray(arr[i]) && typeof arr[i] === 'object' &&  arr[i] !== null )
    objects.push(arr[i]);
}
console.log(objects)
  return objects.length;
}

console.log((countTheObjects([1, [], 3, 4, 5, {}, {}, {}, 'foo'])))
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Array.filter() and Array.isArray() to do this.

Array.filter() will look at each item in the array and keep if it the return value of a callback function is true.

function countTheObjects(arr) {
  return arr.filter((item) => item && typeof item === "object" && !Array.isArray(item)).length;
}

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

8 Comments

Thanks for the response, but it seems to return undefined?
@ah1917 than you did something different than what the answer shows.
That's strange, when I run this in the stack overflow code snippet with "Run Code Snippet" button it returns "3"
@WillD I would add (item) => item && typeof item ...
Yeah it runs fine for me on here, but I've tried on two separate consoles now and still receive undefined?
|
0

You can filter the array based on typeof and also check for array and null.

const countIt = (arr) => arr.filter(item => typeof item === "object" && item !== null && Array.isArray(item) === false).length

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.