计数单词长度与出现javascript

qzwqbdag  于 2023-04-04  发布在  Java
关注(0)|答案(2)|浏览(159)

写一个函数,它接受一个由一个或多个空格分隔的单词组成的字符串,并返回一个显示不同大小单词数量的对象。单词由任何非空格字符序列组成。
这是我目前掌握的情况

const strFrequency = function (stringArr) {
    return stringArr.reduce((count,num) => {
  count [num] = (count[num] || 0) + 1;
    return count;
  },
  {})
  }

  let names = ["Hello world it's a nice day"];

  console.log(strFrequency(names)); // { 'Hello world it\'s a nice day': 1 } I need help splitting the strings
ql3eal8s

ql3eal8s1#

处理:检查它是否是无效的输入,然后返回空白对象,否则通过将其拆分为单词,然后添加到状态对象中相同长度的数组中来处理它。希望这就是你要找的!

const str = "Hello world it's a nice day";

function getOccurenceBasedOnLength(str = ''){
  if(!str){
    return {};
  }
  return str.split(' ').reduce((acc,v)=>{
    acc[v.length] = acc[v.length] ? [...acc[v.length], v] : [v];
    return acc;
  },{});
}

console.log(getOccurenceBasedOnLength(str));

输出

{
  '1': [ 'a' ],
  '3': [ 'day' ],
  '4': [ "it's", 'nice' ],
  '5': [ 'Hello', 'world' ]
}
cx6n0qe3

cx6n0qe32#

//str='The dog jumped over the shipyard fence'

function wordLengths(str){

    const newArrayList=str.split(" ");

    let newStr="";

      for(let i=0;i<newArrayList.length;i++){
        newStr+=newArrayList[i]
      }
     return newStr.length;
}

相关问题