计算出现的单词长度 javascript

Count word length with occurrence javascript

编写一个函数,接受一个由一个或多个 space 分隔的单词组成的字符串,以及 returns 一个显示不同大小的单词数量的对象。单词由非 space 字符的任意序列组成。

这是我目前所拥有的

  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 

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

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' ]
}