In JavaScript, the typeof operator can be used to determine the data type of each element in an array. By iterating through the array and keeping track of each type, we can count how many elements belong to each data type.
- The typeof operator returns the type of a value as a string.
- Array.reduce() can be used to count the occurrences of each data type.
- Array.forEach() can also be used to iterate through the array and maintain the counts.
- Arrays, objects, and null are reported as object by typeof.
Approach 1: Using reduce() Method
In this approach, the reduce() method is used to iterate over the array and store the count of each data type in an object.
Example: Counts the number of elements belonging to each data type in the given array.
let countDtypes = (arr) => {
return arr.reduce((acc, curr) => {
// Get the data type of the current element
let type = typeof curr;
// Increase the count if the type already exists
if (acc[type]) {
acc[type]++;
} else {
// Initialize the type count
acc[type] = 1;
}
return acc;
}, {});
}
let arr = [
function () {},
new Object(),
[],
{},
NaN,
Infinity,
undefined,
null,
0
];
console.log(countDtypes(arr));
Output
{ function: 1, object: 4, number: 3, undefined: 1 }
Approach 2: Using forEach() Method
In this approach, the forEach() method is used to iterate over each element of the array. The typeof operator determines the data type, and an object stores the count for each type.
Example: Counts the occurrences of each data type using forEach().
let countDtypes = (arr) => {
let obj = {};
arr.forEach((val) => {
// Get the data type of the current element
let type = typeof val;
// Increase the count if the type already exists
if (obj[type]) {
obj[type]++;
} else {
// Initialize the type count
obj[type] = 1;
}
});
return obj;
}
let arr = [
function () {},
new Object(),
[],
{},
NaN,
Infinity,
undefined,
null,
0
];
console.log(countDtypes(arr));
Output
{ function: 1, object: 4, number: 3, undefined: 1 }