Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 09 Jul, 2021
Geek Week

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 
}

strong>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
}

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :