当前位置:网站首页>js计算数组中每个元素出现的次数
js计算数组中每个元素出现的次数
2022-08-05 19:09:00 【小绵杨Yancy】
一、要求
// Write a function that takes an array of numbers as argument
// Convert the array to an object
// It should have a key for each unique value of the array
// The corresponding object value should be the number of times the key occurs within the array

二、解
function myFunction(a) {
return a.reduce((acc, cur) => {
return {
...acc, [cur]: acc[cur] + 1 || 1 };
}, {
})
}
还可以通过遍历数组,然后依次将数组的值作为对象的属性,然后通过计算次数,但是远不如reduce优雅。
边栏推荐
猜你喜欢
随机推荐
03 数据库查询、模型查询、多库查询《ThinkPHP6 入门到电商实战》
为什么企业需要使用 Wiki 工具?
有主键索引cpu 还是100%
软链接与硬链接的区别(图文详解)
【每日一题】623. 在二叉树中增加一行
MVC设计思想
Cookie与Session
The MVC design ideas
面试结束前被问「你有哪些要问我的?」该怎么办?这样回答你就凉了
编译器工程师眼中的好代码:Loop Interchange
Win11开机提示音要怎么改?
Alibaba billion-level concurrent system design manual has been open source (2022 latest version)
tiup cluster deploy
RHCE 作业五(DNS解析流程详解)
rhcsa 第二次作业
给echart.js折线图设置滚动条
LVS负载均衡集群
泛型集合
【day7】Scanner类、Random类、ArrayList类
(22年纯享)阿里巴巴十亿级并发系统设计手册已开源









