How to count number of data types in an array in JavaScript ?

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


