6Ortiz
6Ortiz

Reputation: 39

Counting data types in an array in Javascript

I'm trying to count how many different data types are in this array, var arr. The output I am trying to return should be 2.

var arr = [12, 45, 66, 88, true, false]
var count = [];

function check_types(arr) {
  for (i = 0; i <= typeof arr.length; i++) {}
  return count;
}
check_types(arr)

I appreciate the feedback that helps me notice what I did wrong and so that I avoid repeating mistakes in future code. Thank you.

Upvotes: 0

Views: 1548

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386654

You could use an object as hash table for just setting a flag. The count the keys for used types.

var array = [12, 45, 66, 88, true, false],
    types = {};

array.forEach(v => types[typeof v] = true);

console.log(types);
console.log(Object.keys(types).length);

Upvotes: 2

sridhar..
sridhar..

Reputation: 2133

There are couple of mistakes, 1. you need to check data types of element inside array. type of array.length is always number 2. for array , you need to loop till arr.length(i< arr.length)

var arr = [12, 45, 66, 88, true, false]
var count = [];

function check_types(arr) {
  for (i = 0; i <arr.length; i++) {
   let dtype = typeof arr[i]
     if(!count.includes(dtype)) {
     count.push(dtype)
   }
  }
  return count.length;
}
console.log(check_types(arr))
console.log(count)

Upvotes: 0

Phiter
Phiter

Reputation: 14992

This will do the trick

function check_types(arr) {
  var types = {};
  arr.forEach(function(i){
    if (types[typeof i] === undefined)
      types[typeof i] = 1;
    else
      types[typeof i]++;
  });
  return Object.keys(types).length;
}

var arr = [12, 45, 66, 88, true, false];

console.log(check_types(arr));

Creates an object where each key represents a type in the array, and the value of each key is the number of the that type within the array. You don't need these numbers right now, so you can just count the amount of keys in that object.

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138277

The output I am trying to return should be 2.

then why do you assign an array to count and not 0?

Additionally you do typeof arr.length which is "number" and it makes little sense to compare that to an index.


Now to get the number of unique types you could map the array to an array of types, then turn it into a unique Set and get its size:

 return new Set(arr.map(el => typeof el)).size;

Upvotes: 1

Related Questions