Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given an array and the task is to count the number of data types used to create that array.

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




<script>
    // 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));
</script>


 Output:

{
   function: 1,
   number: 3,
   object: 4,
   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




<script>
    // 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));
</script>


Output:

{
  boolean: 1,
  function: 1,
  number: 1,
  object: 2,
  string: 1,
  undefined: 1
}

My Personal Notes arrow_drop_up
Last Updated : 19 Dec, 2022
Like Article
Save Article
Similar Reads
Related Tutorials