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
// JavaScript program to count number of // data types in an array let countDtypes = (arr) => { return arr.reduce((acc, curr) => { // Check if the acc contains the // type or not if (acc[ typeof curr]) { // Increase the type with one acc[ typeof curr]++; } else { /* If acc not contains the type then initialize the type with one */ acc[ typeof curr] = 1 } return acc }, {}) // Initialize with an empty array } let arr = [ function () { }, new Object(), [], {}, NaN, Infinity, undefined, null , 0]; console.log(countDtypes(arr)); |
{ 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
// JavaScript program to count number of // data types in an array let countDtypes = (arr) => { let obj = {} arr.forEach((val) => { // Check if obj contains the type or not if (obj[ typeof val]) { // Increase the type with one obj[ typeof val]++; } else { // Initialize a key (type) into obj obj[ typeof val] = 1; } }) return obj } let arr = [ function () { }, new Object(), [], {}, NaN, Infinity, undefined, null , 0 ]; console.log(countDtypes(arr)); |
{ function: 1, object: 4, number: 3, undefined: 1 }