How to count number of data types in an array in JavaScript ?
Last Updated :
23 Jun, 2023
Given an array and the task is to count the number of data types used to create that array in JavaScript.
Example:
Input: [1, true, "hello", [], {}, undefined, function(){}]
Output: {
boolean: 1,
function: 1,
number: 1,
object: 2,
string: 1,
undefined: 1
}
Input: [function(){}, new Object(), [], {},
NaN, Infinity, undefined, null, 0]
Output: {
function: 1,
number: 3,
object: 4,
undefined: 1
}
Approach 1: In this approach, We use the Array.reduce() method and initialize the method with an empty object.
Javascript
let countDtypes = (arr) => {
return arr.reduce((acc, curr) => {
if (acc[ typeof curr]) {
acc[ typeof curr]++;
} else {
acc[ typeof curr] = 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: In this approach, we use the Array.forEach() method to iterate the array. And create an empty array and at every iteration, we check if the type of present iteration present in the newly created object or not. If yes then just increase the type with 1 otherwise create a new key by the name of the type and initialize with 1.
Javascript
let countDtypes = (arr) => {
let obj = {}
arr.forEach((val) => {
if (obj[ typeof val]) {
obj[ typeof val]++;
} else {
obj[ typeof val] = 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 }
Share your thoughts in the comments
Please Login to comment...