统计数组中元素出现次数
reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
reducer 函数接收4个参数:
1.Accumulator (acc) (累计器)
2.Current Value (cur) (当前值)
3.Current Index (idx) (当前索引)
4.Source Array (src) (源数组)
您的 reducer 函数的返回值分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。
1
2
3
4
5
const count = arr => arr.reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
},{})
count([1,1,2,3,1,1,2]); // {1:4,2:2,3:1}