简体   繁体   English

计数字长出现 javascript

[英]Count word length with occurrence javascript

Write a function that takes a string consisting of one or more space separated words, and returns an object that shows the number of words of different sizes.编写一个 function,它接受一个由一个或多个空格分隔的单词组成的字符串,并返回一个 object,它显示不同大小的单词的数量。 Words consist of any sequence of non-space characters.单词由任何非空格字符序列组成。

This is what I have so far这是我到目前为止所拥有的

  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 

Process: Check if it is an invalid input then return blank object else process it by splitting it into words then adding into an array of the same length in state object.处理:检查是否为无效输入,然后返回空白 object 否则通过将其拆分为单词然后添加到 state object 中相同长度的数组来处理它。 Hope this is what you were looking for!希望这就是你要找的!

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));

Output Output

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM