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'])))
CodePudding user response:
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'])))
CodePudding user response:
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']));
CodePudding user response:
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