当前位置:网站首页>Counts the number of occurrences of each character in the string
Counts the number of occurrences of each character in the string
2022-04-23 06:50:00 【KK should continue to work hard】
Count the number of occurrences of each character in the string
subject :
Count the number of times each character appears in a string , And return the letter with the most occurrences and the corresponding number of times
answer :
utilize reduce function , Think of each character as an empty box , After traversing, the value is transferred to the empty box , Finally, determine how much is in the empty box
var str="helloworld";
var arr=str.split("");
var result=arr.reduce(
function(prev,elem){
// When you get to this number, add... To this number 1 Time
if(prev[elem]===undefined){
prev[elem]=1;
}else{
prev[elem]+=1;
}
return prev;
},
{
}
)
var char,count;
// Traverse result Each member in
for(var key in result){
// The first time, if not
if(char===undefined){
char=key;
count=result[key];
}else{
// otherwise , Start making comparisons
if(result[key]>count){
char=key;
count=result[key];
}
}
}
console.log(`${
char} The most frequent occurrence , Altogether ${
count} Time `);
function strNum(str){
let obj = {
};
for(let i=0;i<str.length;i++){
let value = str.charAt(i)
if(obj[value]){
obj[value]++
}else{
obj[value] = 1
}
}
let word = null
let temp = 0
for(let key in obj){
if(obj[key]>temp){
temp = obj[key]
word = key
}
}
return [word, temp].join(' ')
}
console.log(strNum('helloword'));
return Return multiple values
- return {a,b,c}
- return [a,b,c]
Knowledge point :reduce()、 loop
版权声明
本文为[KK should continue to work hard]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230551364072.html
边栏推荐
猜你喜欢
Analysis of fixed point PID code of FOC motor Library
查漏补缺(三)
Principle and characteristic analysis of triode
【ES6】 Promise相关(事件循环,宏/微任务,promise,await/await)
el-table添加序号
MOS tube characteristics and conduction process
数据可视化进一步学习
VHDL finite state machine (FSM) code example
微信小程序之点击取消,返回上页,修改上页的参数值,let pages=getCurrentPages() let prevPage=pages[pages.length - 2] // 上一页的数据
C# Task.Delay和Thread.Sleep的区别
随机推荐
SiteServer CMS5.0使用总结
ASP.NET CORE 依赖注入服务生命周期
百度地图案例-修改地图样式
如何使用input表单向服务发送(占用较小)图片文件(body传输)?涉及到FileReader内置对象
统计字符串中每个字符出现的次数
【批量更改mysql表以及表中字段对应的编码】
Overview of node file system and buffer
Set与Map
Arm common assembly instructions
Special register C51 / C52
查漏补缺(二)
Color string conversion
WebAPI+Form表单上传文件
input文件上传
查漏补缺(五)
Analysis and setting of dead time
New features of ES6
excel快速自动填充空白单元格上一行的内容
POJ-The Unique MST
Router对象、Route对象、声明式导航、编程式导航