当前位置:网站首页>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
边栏推荐
猜你喜欢
Makefile foundation, common functions and general makefile
FOC SVPWM function pwmc_ Setphasevoltage parsing
C# webpai 路由详解
查漏补缺(三)
Analysis of fixed point PID code of FOC motor Library
Overview of node file system and buffer
js中entries(),keys(),values() , some(), Object.assign()遍历数组用法
C# Task.Delay和Thread.Sleep的区别
js获取链接?后边的参数名称或者值,根据url ?后的参数做判断
Principle and characteristic analysis of triode
随机推荐
锚点定位——如何设置锚点居页面顶部距离,锚点定位并距离顶部一定偏移
若依框架从零开始
ES6的新特性
Set与Map
freeCodeCamp----prob_calculator练习
1-1 NodeJS
The difference between VaR, let and Const
Special register C51 / C52
Devexpress Gridview 添加全选列
1-4 NodeJS的安装之配置可执行脚本
【关于数据库的简易认识】
算数表达式
浏览器中堆栈内存的底层处理
元素计算距离与event事件对象
js根据名字将数组对象中名字相同的项组成一个相同的数组
元编程,代理Proxy与反射Reflect
.Net Core 下使用 Quartz —— 【3】作业和触发器之作业传参
导入文件时候 new FormData()
百度地图案例-修改地图样式
条形码与二维码的生成