本文介绍了JavaScript的集团通过阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Let's say I have simple JavaScript array like the following:
var array = ['Car', 'Car', 'Truck', 'Boat', 'Truck'];
I want to group and count of each so I would expect a key/value map of:
{
Car : 2,
Truck : 2,
Boat : 1
}
解决方案
var arr = [ 'Car', 'Car', 'Truck', 'Boat', 'Truck' ];
var hist = {};
arr.map( function (a) { if (a in hist) hist[a] ++; else hist[a] = 1; } );
console.log(hist);
results in
{ Car: 2, Truck: 2, Boat: 1 }
This works, too:
hist = arr.reduce( function (prev, item) {
if ( item in prev ) prev[item] ++;
else prev[item] = 1;
return prev;
}, {} );
这篇关于JavaScript的集团通过阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!