-1

Is there a way to find the data type composition of an array without using a loop like below

var anArray = [
        52,
        "A string",
        new Date(),
        "spatula"
    ],
    typeVar,
    compOfArray = {};

for (var i in anArray) {
    typeVar = typeof anArray[i];
    if (!compOfArray[typeVar])   compOfArray[typeVar] = true;
    else                         compOfArray[typeVar] += 1;
}
jophab
  • 5,356
  • 14
  • 41
  • 60
Jason
  • 779
  • 1
  • 9
  • 30
  • No, there isn't a way to do that without a loop. Btw, a `for..in` loop is [the wrong way](http://stackoverflow.com/q/500504/5743988) to iterate over an array. – 4castle Jan 21 '17 at 00:15
  • 1
    `compOfArray = anArray.reduce((obj,val)=> (obj[t=typeof val] = (obj[t]|0)+1, obj), {})` – Washington Guedes Jan 21 '17 at 00:18

2 Answers2

0

No, you can check any array methods by using Array.prototype in the console or check MDN

teaflavored
  • 440
  • 4
  • 9
0

You can use the reduce-function to build up an object which keeps track of how many of each types are in the array:

var compOfArray = anArray.reduce(function(a,b){
  typeof b in a ? a[typeof b]++ : a[typeof b] = 1;
  return a
},{});
Thomas Altmann
  • 1,744
  • 2
  • 11
  • 16