比如我有一个这样的数组:[ 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 5, 5, 6, 6, 7, 8, 9 ]我希望能够计算,比如数字“1”有几个,“2”有几个,并返回他们的个数(比如数字“1”在这里有3个,就返回3)。谢谢大神~
2 回答

JasonLamv_t
TA贡献1条经验 获得超1个赞
let arr = [ 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 5, 5, 6, 6, 7, 8, 9 ] let res = arr.filter(el => el == 1).length
可以使用filter对数组进行筛选,再使用length计算个数,仅支持统计单类数量

www说
TA贡献1775条经验 获得超8个赞
var t = [ 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 5, 5, 6, 6, 7, 8, 9 ];
var res = {};
t.forEach(function(e){
res[e] = res[e]>=1?res[e]+1:1
});
console.log(res);
添加回答
举报
0/150
提交
取消