面试//统计单词数量,降序输出
作者:互联网
注意代码规范
注意函数不要嵌套太深
arr.reduce(fun, initialVal)
// function-统计对象属性数量
function getSum(res, currentVal) {
if(currentVal in res){
res[currentVal]++
}else{
res[currentVal] = 1
}
return res
}
// function-逐个输出
function outputEach(arr){
arr.map(r=>{
console.log(r.label,r.value)
})
}
// function-输出单词及数量
function outputLettersNum(str){
// 切割字符串为数组
var arr = str.split(' ')
// 遍历统计每个letter数量
let res = arr.reduce(getSum,{})
// 排序
var result = Object.keys(res).sort((a,b)=>{
return res[b] - res[a]
})
result = result.map(r=>{
return {"label":r,"value":res[r]}
})
// 逐个输出
return outputEach(result)
}
var str1 = "There are moments in life when you miss someone be what you want to be because you have only one life and one chance to do all the things you want to do"
console.log(outputLettersNum(str1))
标签:function,arr,return,res,降序,currentVal,单词,面试,result 来源: https://blog.csdn.net/weixin_37877794/article/details/119357866