Counting the occurrences / frequency of array elements

前端 未结 30 2101
甜味超标
甜味超标 2020-11-21 06:47

In Javascript, I\'m trying to take an initial array of number values and count the elements inside it. Ideally, the result would be two new arrays, the first specifying each

30条回答
  •  暖寄归人
    2020-11-21 07:31

    If you are using underscore you can go the functional route

    a = ['foo', 'foo', 'bar'];
    
    var results = _.reduce(a,function(counts,key){ counts[key]++; return counts },
                      _.object( _.map( _.uniq(a), function(key) { return [key, 0] })))
    

    so your first array is

    _.keys(results)
    

    and the second array is

    _.values(results)
    

    most of this will default to native javascript functions if they are available

    demo : http://jsfiddle.net/dAaUU/

提交回复
热议问题