组数组并计数 [英] group array and get count
本文介绍了组数组并计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有这样的数组:
[
"foo",
"bar",
"foo"
"bar",
"bar",
"bar",
"zoom"
]
我想对它进行分组,这样我就可以得到一个计数:
I want to group it so I can get a count like so:
{
"foo": 2,
"bar": 4,
"zoom": 1
}
有可以执行此操作的实用程序吗?
is there a utility that can do this?
推荐答案
只需使用函数Array.prototype.reduce
.
let array = [ "foo", "bar", "foo", "bar", "bar", "bar", "zoom"],
result = array.reduce((a, c) => (a[c] = (a[c] || 0) + 1, a), Object.create(null));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于组数组并计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文